How to write all class variables to disk with dill

2019-07-26 01:52发布

问题:

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.