import cPickle
class Foo(object):
def __init__(self):
self._data = {'bar': 'baz'}
def __getattr__(self, name):
assert hasattr(self, '_data')
return self._data[name]
# I even had to define this just to stop KeyError: '__getstate__'
def __getstate__(self):
return self.__dict__
foo = Foo()
bar = cPickle.dumps(foo)
cPickle.loads(bar)
This raises an assertion error.
I thought pickle
/cPickle
just turns __dict__
into a string when dumping and then uses that string to set the __dict__
of the new object directly when loading. Why would dumps
need to call bar.__getattr__
? How can I change Foo
to avoid that?