[Python-ideas] Put default setstate and getstate on object for use in coöperative inheritance.

Steven D'Aprano steve at pearwood.info
Sat Jun 7 11:10:50 CEST 2014


On Sat, Jun 07, 2014 at 02:10:15AM -0400, Neil Girdhar wrote:
> Hi Steven,
> 
> If you don't know about getstate and setstate, I suggest you take a look at
> the documentation:
> https://docs.python.org/3.3/library/pickle.html#object.__getstate__.

I know about getstate as it regards to pickle, that's why I asked if you 
were talking about serialization. Unfortunately you never mentioned 
pickle, or copy, you talked about cooperative inheritence which is a 
generic concept that applies much more broadly than just copying or 
serializing instances.


> Besides allowing objects to be pickled, providing these methods allows
> them to be copied with the copy module.

objects can already be copied and pickled:

py> import copy, pickle
py> x = object()
py> copy.copy(x)
<object object at 0xb7ce9588>
py> pickle.dumps(x)
b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'

Copying and pickling are defined by protocols, not inheritence, so 
there's no need for a single root method.  As the documentation states, 
you only need to define a __getstate__ and __setstate__ method when the 
default protocol behaviour is not sufficient for your class, so adding 
these methods to object is unnecessary.

There's a historical reason for doing it this way: in Python 2, not 
everything inherits from object.


-- 
Steven


More information about the Python-ideas mailing list