代码之家  ›  专栏  ›  技术社区  ›  adum

python:无法pickle模块对象错误

  •  8
  • adum  · 技术社区  · 14 年前

    我正在尝试pickle一个大类并得到“typeerror:cannotpickle module objects”。尽管浏览了一下网络,我还是搞不清这到底是什么意思。我不确定是哪个“模块对象”引起了麻烦。有办法找到罪犯吗?堆栈跟踪似乎没有任何指示。

    2 回复  |  直到 8 年前
        1
  •  7
  •   unutbu    14 年前

    我可以这样复制错误消息:

    import cPickle
    
    class Foo(object):
        def __init__(self):
            self.mod=cPickle
    
    foo=Foo()
    with file('/tmp/test.out', 'w') as f:
        cPickle.dump(foo, f) 
    
    # TypeError: can't pickle module objects
    

    是否有引用模块的类属性?

        2
  •  5
  •   Mike McKerns    10 年前

    python无法pickle模块对象是真正的问题。有什么好理由吗?我不这么认为。模块对象不可访问导致了python作为并行/异步语言的脆弱性。如果要pickle模块对象或python中的几乎任何对象,请使用 dill .

    Python 3.2.5 (default, May 19 2013, 14:25:55) 
    [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import dill
    >>> import os
    >>> dill.dumps(os)
    b'\x80\x03cdill.dill\n_import_module\nq\x00X\x02\x00\x00\x00osq\x01\x85q\x02Rq\x03.'
    >>>
    >>>
    >>> # and for parlor tricks...
    >>> class Foo(object):
    ...   x = 100
    ...   def __call__(self, f):
    ...     def bar(y):
    ...       return f(self.x) + y
    ...     return bar
    ... 
    >>> @Foo()
    ... def do_thing(x):
    ...   return x
    ... 
    >>> do_thing(3)
    103 
    >>> dill.loads(dill.dumps(do_thing))(3)
    103
    >>> 
    

    得到 小茴香 在这里: https://github.com/uqfoundation/dill