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

Kevin Jacobs jacobs@penguin.theopalgroup.com
Mon, 9 Dec 2002 10:20:09 -0500 (EST)


On Mon, 9 Dec 2002, Guido van Rossum wrote:
> 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.

Here is my code for dealing with this "feature":

  def __getstate__(self):
    state = getattr(self, '__dict__', {}).copy()
    for obj in type(self).mro():
      for name in getattr(obj,'__slots__',()):
        if hasattr(self, name):
          state[name] = getattr(self, name)
    return state

  def __setstate__(self, state):
    for key,value in state.items():
      setattr(self, key, value)

I also have a meta-class that adds these methods for derived objects, since
the core decided to play it overly safe on this issue.

-Kevin

--
Kevin Jacobs
The OPAL Group - Enterprise Systems Architect
Voice: (216) 986-0710 x 19         E-mail: jacobs@theopalgroup.com
Fax:   (216) 986-0714              WWW:    http://www.theopalgroup.com