dict subclass and pickle bug (?)
Christian Heimes
lists at cheimes.de
Sun Dec 7 14:18:21 EST 2008
James Stroud wrote:
> Hello All,
>
> I subclassed dict and overrode __setitem__. When instances are
> unpickled, the __setstate__ is not called before the keys are assigned
> via __setitem__ in the unpickling protocol.
>
> I googled a bit and found that this a bug filed in 2003:
>
> http://bugs.python.org/issue826897
>
> It is still "open" with "normal" priority.
>
> Am I missing something? Is there a workaround for this bug that makes
> fixing it pointless or has it just fallen through the cracks for the
> last 5 years?
Try this:
def __newobj__(cls, *args):
return cls.__new__(cls, *args)
class DictPlus(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.extra_thing = ExtraThingClass()
def __setitem__(self, k, v):
do_something_with(self.extra_thing, k, v)
dict.__setitem__(self, k, v)
def __setstate__(self, state):
dict.update(self, state[0])
self.__dict__.update(state[1])
def __reduce__(self):
state = (dict(self), self.__dict__)
return (__newobj__, (self.__class__,), state)
Christian
More information about the Python-list
mailing list