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?
According the documentation for cPickle: http://docs.python.org/library/pickle.html
Since you are trying to assert that
hasattr(self, '_data')is True, I believe that you need to use__getinitargs__()or__getnewargs__(). This is because when using pickle, a classes__init__method is not called.