attributeError:can can pickle local对象'< gt;。
我正在尝试腌制一本使用以下方式创建的嵌套词典:
collections.defaultdict(lambda: collections.defaultdict(int))
我的简化代码是这样的:
class A:
def funA(self):
#create a dictionary and fill with values
dictionary = collections.defaultdict(lambda: collections.defaultdict(int))
...
#then pickle to save it
pickle.dump(dictionary, f)
但是它给出了错误:
AttributeError: Can't pickle local object 'A.funA.<locals>.<lambda>'
在打印字典后,它显示出来:
defaultdict(<function A.funA.<locals>.<lambda> at 0x7fd569dd07b8> {...}
我尝试在该函数中将字典全局变成,但错误是相同的。 我感谢对此问题的任何解决方案或见解。谢谢!
I am trying to pickle a nested dictionary which is created using:
collections.defaultdict(lambda: collections.defaultdict(int))
My simplified code goes like this:
class A:
def funA(self):
#create a dictionary and fill with values
dictionary = collections.defaultdict(lambda: collections.defaultdict(int))
...
#then pickle to save it
pickle.dump(dictionary, f)
However it gives error:
AttributeError: Can't pickle local object 'A.funA.<locals>.<lambda>'
After I print dictionary it shows:
defaultdict(<function A.funA.<locals>.<lambda> at 0x7fd569dd07b8> {...}
I try to make the dictionary global within that function but the error is the same.
I appreciate any solution or insight to this problem. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Pickle
记录对功能(模块和功能名称)的引用,而不是功能本身。当取消打印时,它将加载模块并按名称获取功能。lambda
创建没有名称的匿名函数对象,并且加载程序找不到。解决方案是切换到命名函数。pickle
records references to functions (module and function name), not the functions themselves. When unpickling, it will load the module and get the function by name.lambda
creates anonymous function objects that don't have names and can't be found by the loader. The solution is to switch to a named function.正如@tdlaney所解释的那样,
lambda
创建一个无法腌制的匿名功能。最简洁的解决方案是将lambda
替换为partial
(无需新功能):As @tdlaney explained,
lambda
creates an anonymous function which can't be pickled. The most concise solution is to replacelambda
withpartial
(no new function needed):