[Python-Dev] __getstate__() not inherited when __slots__ present

Guido van Rossum guido@python.org
Mon, 09 Dec 2002 10:13:45 -0500


> If a class and its superclass both define __slots__, it appears that
> __getstate__() is not inherited from the superclass.  Example:
> 
> """
> class Base (object):
>     __slots__ = []
> 
>     def __getstate__ (self):
>         return tuple([getattr(self, attr) for attr in self.__slots__])
> 
> class Thing (Base):
>     __slots__ = ['a', 'b']
> 
>     def __init__ (self):
>         self.a = 42
>         self.b = "boo!"
> 
> abstract = Base()
> thing = Thing()
> 
> print abstract.__getstate__
> print thing.__getstate__
> """
> 
> When I run this with a not-quite-current CVS Python:
> 
>   <bound method Base.__getstate__ of <__main__.Base object at 0x401f73b8>>
>   <built-in function __getstate__>
> 
> The upshot of this is that I can't just define one __getstate__() in the
> superclass of a bunch of __slots__-using classes -- I guess I'll have to
> set __getstate__ manually for each class.  ;-(  If this is a feature, is
> it documented anywhere?
> 
> (BTW, I see the same behaviour with Python 2.2.2.)

It's a feature.  When a class defines __slots__ and not __getstate__,
it gets a bogus __getstate__ that always raises an exception.  The
assumption is that the base class __getstate__ doesn't know about the
subclass slots and hence is unlikely to be able to retrieve them
correctly.

BTW, your code for accessing the slots by saying self.__slots__
doesn't work in general: self.__slots__ returns the __slots__ variable
of the most derived class only.

--Guido van Rossum (home page: http://www.python.org/~guido/)