[Python-ideas] new pickle semantics/API
tomer filiba
tomerfiliba at gmail.com
Thu Jan 25 22:15:04 CET 2007
there's a bug in the copy function that i wanted to fix:
def copy(obj):
cls, state = obj.__getstate__()
return cls.__setstate__(state)
also, but there's a reason why __getstate__ returns
"(cls, state)" rather than just "state", and that's to keep
things agile. i don't want to be necessarily tightly-coupled
to a certain type.
the cls will be used to reconstruct the object (cls.__setstate__),
much like the function returned by __reduce__, so normally,
__getstate__ would just return self.__class__ for cls.
but there are times, especially when object proxies are
involved, that we may want to "lie" about the actual type,
i.e., use a different type to reconstruct the object with.
here's an example that shows why:
class ListProxy:
...
def __getstate__(self):
return list, self._value
instances of ListProxy, when stored in a file (i.e., shelf),
want to be pickled by value. moreover, when they are
loaded from a file, they want to loaded as actual lists,
not proxies, as the proxied object is long lost.
so returning a tuple of (cls, state) gives more freedom to
frameworks and other utilities. of course, again, most code
would just return (self.__class__, state)
-tomer
More information about the Python-ideas
mailing list