Python:用一些不可拾取的项目腌制字典 [英] Python: Pickling a dict with some unpicklable items

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

问题描述

我有一个对象gui_project,它的属性为.namespace,这是名称空间字典. (即,从字符串到对象的字典.)

I have an object gui_project which has an attribute .namespace, which is a namespace dict. (i.e. a dict from strings to objects.)

(在类似IDE的程序中使用,可让用户在Python shell中定义自己的对象.)

(This is used in an IDE-like program to let the user define his own object in a Python shell.)

我想对这个gui_project以及名称空间进行腌制.问题是,命名空间中的某些对象(即.namespace dict的值)不是可拾取的对象.例如,其中一些引用了wxPython小部件.

I want to pickle this gui_project, along with the namespace. Problem is, some objects in the namespace (i.e. values of the .namespace dict) are not picklable objects. For example, some of them refer to wxPython widgets.

我想过滤掉无法腌制的对象,也就是说,将它们从腌制版中排除.

I'd like to filter out the unpicklable objects, that is, exclude them from the pickled version.

我该怎么做?

(我试图做的一件事是对值进行逐一处理并尝试使它们腌制,但是发生了一些无限递归,因此我需要对此保持安全.)

(One thing I tried is to go one by one on the values and try to pickle them, but some infinite recursion happened, and I need to be safe from that.)

(我现在确实实现了GuiProject.__getstate__方法,以除去除namespace之外的其他不可拾取的东西.)

(I do implement a GuiProject.__getstate__ method right now, to get rid of other unpicklable stuff besides namespace.)

推荐答案

我最终使用Shane Hathaway的方法编写了自己的解决方案.

I ended up coding my own solution to this, using Shane Hathaway's approach.

此处是代码. (查找CutePicklerCuteUnpickler.) GarlicSim 的一部分,因此您可以通过

Here's the code. (Look for CutePickler and CuteUnpickler.) Here are the tests. It's part of GarlicSim, so you can use it by installing garlicsim and doing from garlicsim.general_misc import pickle_tools.

如果要在Python 3代码上使用它,请使用 garlicsim的Python 3分支.

If you want to use it on Python 3 code, use the Python 3 fork of garlicsim.

这篇关于Python:用一些不可拾取的项目腌制字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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