我惊讶地发现 python(版本 3.2.2)拒绝 pickle 一个对象,因为它的字典包含对 Ellipsis
的引用。其他built-in constants , pickle 很高兴与 False
、True
和 None
一起工作,如 pickle documentation 中明确说明的那样, 但也会因 NotImplemented
而窒息。
Python 3.2.2 (default, Sep 5 2011, 21:17:14)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> pickle.dumps(True)
b'\x80\x03\x88.'
>>> pickle.dumps(False)
b'\x80\x03\x89.'
>>> pickle.dumps(None)
b'\x80\x03N.'
>>> pickle.dumps(Ellipsis)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'ellipsis'>: attribute lookup builtins.ellipsis failed
>>> pickle.dumps(NotImplemented)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'NotImplementedType'>: attribute lookup builtins.NotImplementedType failed
为了完整起见,在不太有用的内置常量中,__debug__
只是一个 bool 值,因此不会造成任何问题; copyright
、license
和 credits
有效(它们的类型是 site._Printer
); quit
和 exit
没有(它们的类型是 site.Quitter
,无法找到,因为它是在函数内部定义的)。
谁能解释为什么这是 - Ellipsis
和 NotImplemented
肯定没有被忽略?我能找到的唯一相关信息是this bug ,它提示 NoneType
(即 type(None)
)不可 picklable。其中一位评论者提到 type(Ellipsis)
和 type(NotImplemented)
不能被 pickle,显然没有注意到它们的实例也不能被 pickle。
最佳答案
python 绝对没有理由不 pickle 像 Ellipsis
和 NotImplemented
这样的东西,坦率地说,不让它们 picklable 导致 python 作为并行/异步的脆弱性语。您可以使用 dill
来 pickle 这些类型的对象,这是 pickle
的替代品。是的,我知道这是一个温和的咆哮,但我认为你的目标代码中的 NotImplemented
不应该阻止你使用 multiprocessing
或并行 python 的其他一些......或保存 python session 的状态以备后用……或其他任何方式。
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
>>> dill.dumps(True)
b'\x80\x03\x88.'
>>> dill.dumps(False)
b'\x80\x03\x89.'
>>> dill.dumps(None)
b'\x80\x03N.'
>>> dill.dumps(Ellipsis)
b'\x80\x03cdill.dill\n_eval_repr\nq\x00X\x08\x00\x00\x00Ellipsisq\x01\x85q\x02Rq\x03.'
>>> dill.dumps(NotImplemented)
b'\x80\x03cdill.dill\n_eval_repr\nq\x00X\x0e\x00\x00\x00NotImplementedq\x01\x85q\x02Rq\x03.'
在这里获取 dill
:https://github.com/uqfoundation/dill
关于python - 为什么不能 pickle Ellipsis 和 NotImplemented?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8973238/