[issue6827] deepcopy erroneously doesn't call __setstate__ if __getstate__ returns empty dict

Amaury Forgeot d'Arc report at bugs.python.org
Thu Sep 3 13:30:55 CEST 2009


Amaury Forgeot d'Arc <amauryfa at gmail.com> added the comment:

This is precisely documented here:
http://docs.python.org/library/pickle.html#object.__setstate__
"Note: For new-style classes, if __getstate__() returns a false value,
the __setstate__() method will not be called."

If you want some default value even when the state is empty, you could
set it in the __new__ method:
[__new__ is always called, but __init__ is skipped by the copy protocol]

class A(object):
    def __new__(cls):
        self = super(cls, A).__new__(cls)
        self.a = 1
        return self
    def __setstate__(self, d):
        self.__dict__.update(d)
    def __getstate__(self):
        d = self.__dict__.copy()
        d.pop('a')
        return d

The __setstate__ is even not necessary here, since it implements the
default behaviour.

----------
nosy: +amaury.forgeotdarc
resolution:  -> works for me
status: open -> pending

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6827>
_______________________________________


More information about the Python-bugs-list mailing list