Pickle failed __getstate__ on my customized class inherited dict

Peter Otten __peter__ at web.de
Wed Nov 20 04:00:03 EST 2019


lampahome wrote:

> I make a class Wrapper inherited from dict and met problem when I want to
> pickle it.
> 
> Is there anyway to make __getstate__ of Wrapper to output a normal
> dict?(Output a dict will help pickleing easily)
> 
> 
> === code ===
> import pickle
> class Wrapper(dict):
>     def __getattr__(self, attr):
>         return self[attr]
>     def __getstate__(self):
>         # blablabla
> 
> d=Wrapper(zip((1,2), (3,4)))
> pickle.dumps(d)
> === code ===
> 
> When I tried overwrite __getstate__ to below:
>     def __getstate__(self):
>         return self.__repr__()
> pickle it will shows:
> b'\x80...__main__...Wrapper...' <- I don't know why it shows the class
> name. That makes me confused.

The class has to be remembered for unpickling. If you replace Wrapper with 
dict -- which is possible with __reduce__() -- the unpickled object will be 
a plain dict:

>>> class Wrapper(dict):
...     def __reduce__(self):
...         return dict, (dict(self),)
... 
>>> w = Wrapper("ab cd ef".split())
>>> w
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> type(w)
<class '__main__.Wrapper'>
>>> import pickle
>>> pickle.dumps(w)
b'\x80\x03cbuiltins\ndict\nq\x00}q\x01(X\x01\x00\x00\x00aq\x02X\x01\x00\x00\x00bq\x03X\x01\x00\x00\x00cq\x04X\x01\x00\x00\x00dq\x05X\x01\x00\x00\x00eq\x06X\x01\x00\x00\x00fq\x07u\x85q\x08Rq\t.'
>>> v = pickle.loads(_)
>>> v
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> type(v)
<class 'dict'>




More information about the Python-list mailing list