为什么我可以 pickle typing.NamedTuple
时不 pickle collections.namedtuple
?我该如何 pickle NamedTuple
?
这段代码显示了到目前为止我已经尝试过的内容:
from collections import namedtuple
from typing import NamedTuple
PersonTyping = NamedTuple('PersonTyping', [('firstname',str),('lastname',str)])
PersonCollections = namedtuple('PersonCollections', ['firstname','lastname'])
pt = PersonTyping("John","Smith")
pc = PersonCollections("John","Smith")
import pickle
import traceback
try:
with open('personTyping.pkl', 'wb') as f:
pickle.dump(pt, f)
except:
traceback.print_exc()
try:
with open('personCollections.pkl', 'wb') as f:
pickle.dump(pc, f)
except:
traceback.print_exc()
在 shell 上输出:
$ python3 prova.py
Traceback (most recent call last):
File "prova.py", line 16, in <module>
pickle.dump(pt, f)
_pickle.PicklingError: Can't pickle <class 'typing.PersonTyping'>: attribute lookup PersonTyping on typing failed
$
最佳答案
这是一个错误。我已经打开了一张票:http://bugs.python.org/issue25665
问题在于,在创建类时, namedtuple
函数通过从调用框架的全局变量中查找__module__
属性来设置其__name__
属性。在这种情况下,调用者是typing.NamedTuple
。
result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
因此,在这种情况下,最终将其设置为
'typing'
。>>> type(pt)
<class 'typing.PersonTyping'> # this should be __main__.PersonTyping
>>> type(pc)
<class '__main__.PersonCollections'>
>>> import typing
>>> typing.NamedTuple.__globals__['__name__']
'typing'
修复:
代替这个,
NamedTuple
函数应该自己设置它:def NamedTuple(typename, fields):
fields = [(n, t) for n, t in fields]
cls = collections.namedtuple(typename, [n for n, t in fields])
cls._field_types = dict(fields)
try:
cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return cls
现在,您还可以执行以下操作:
PersonTyping = NamedTuple('PersonTyping', [('firstname',str),('lastname',str)])
PersonTyping.__module__ = __name__
关于python - 为什么我可以 pickle collections.namedtuple的同时不 pickle type.NamedTuple?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33796490/