How to write all class variables to disk with dill?

孤人 提交于 2019-12-11 04:56:37

问题


I'm trying to store a couple of objects for restart purposes in a code I'm writing. They are fairly complex, with several layers of classes contained within them, including classes that use class variables. I need this all to be restored when I dill.load() it back up.

Unfortunately, there's a very specific thing that I'm doing that seems to not work with dill.

I've created a test case that exhibits the problem:

basic.py:

class Basic(object):
    x = 10
    def __init__(self, initial=False):
        super(Basic, self).__init__()
        self.y = 4
        Basic.z = 5

make_dill.py:

import dill
from basic import Basic
b = Basic()
with open('basic', 'wb') as f:
    dill.dump(b, f)
with open('basic', 'rb') as f:
    b = dill.load(f)
print('basic', b.x, b.y, b.z)

un_dill.py:

import dill
with open('basic', 'rb') as f:
    b = dill.load(f)
print('basic', b.x, b.y, b.z)

It works fine when it is all run from the same file (make_dill.py), but when I try to read the file basic in un_dill.py:

AttributeError: 'Basic' object has no attribute 'z'

So for some reason it isn't capturing the class variable z that is assigned during initialization of an instance. It does however capture the class variable x that is assigned right in the class definition.

What am I missing here? I need to save the complete state of these objects.

In the sparse dill documentation, it says

In addition to pickling python objects, dill provides the ability to save the state of an interpreter session in a single command.

but I can't figure out how to do that.

来源:https://stackoverflow.com/questions/42752716/how-to-write-all-class-variables-to-disk-with-dill

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!