用Python腌制weakref [英] Pickling weakref in Python

查看:458
本文介绍了用Python腌制weakref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python还是很陌生,甚至对酸洗也比较新.我有一个带有 __getnewargs__() 的类Vertex(ScatterLayout):

I am still pretty new to Python and even newer to pickling. I have a class Vertex(ScatterLayout) with a __getnewargs__():

def __getnewargs__(self):
    return (self.pos, self.size, self.idea.text)

我的理解是,这将使泡菜从__getnewargs__()而不是对象的字典中泡菜.

My understanding is that this will cause the pickle to pickle the object from __getnewargs__() rather than the object's dictionary.

通过以下方法(在另一个类MindMapApp(App)中)调用泡菜:

The pickle is called in the following method (in a different class MindMapApp(App)):

def save(self):
    vertices = self.mindmap.get_vertices()
    edges = self.mindmap.get_edges()

    output = open('mindmap.pkl', 'wb')

    #pickle.dump(edges, output, pickle.HIGHEST_PROTOCOL)
    pickle.dump(vertices, output, pickle.HIGHEST_PROTOCOL)

    output.close()

当我调用save()方法时,出现以下错误:

When I call the save() method I get the following error:

pickle.PicklingError: Can't pickle <type 'weakref'>: it's not found as __builtin__.weakref

我缺少或不了解什么?我也尝试过实现__getstate__()/__setstate__(state)组合,结果相同.

What am I missing or not understanding? I have also tried implementing the __getstate__() / __setstate__(state) combination, with the same result.

推荐答案

您当然可以腌制weakref,也可以腌制dictlist. 但是,实际上它们包含的内容很重要.如果dictlist包含不可拾取的intem,则酸洗将失败.如果要腌制weakref,则必须使用dill而不是pickle.但是,未选择的weakref会反序列化为无效引用.

You definitely can pickle a weakref, and you can pickle a dict and a list. However, it actually matters what they contain. If the dict or list contains unpicklable intems, then the pickling will fail. If you want to pickle a weakref, you have to use dill and not pickle. The unpicked weakref however deserialize as dead references.

>>> import dill
>>> import weakref
>>> dill.loads(dill.dumps(weakref.WeakKeyDictionary()))
<WeakKeyDictionary at 4528979192>
>>> dill.loads(dill.dumps(weakref.WeakValueDictionary()))
<WeakValueDictionary at 4528976888>
>>> class _class:
...   def _method(self):
...     pass
... 
>>> _instance = _class()
>>> dill.loads(dill.dumps(weakref.ref(_instance)))
<weakref at 0x10d748940; dead>
>>> dill.loads(dill.dumps(weakref.ref(_class())))
<weakref at 0x10e246a48; dead>
>>> dill.loads(dill.dumps(weakref.proxy(_instance)))
<weakproxy at 0x10e246b50 to NoneType at 0x10d481598>
>>> dill.loads(dill.dumps(weakref.proxy(_class())))
<weakproxy at 0x10e246ba8 to NoneType at 0x10d481598>

这篇关于用Python腌制weakref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆