[Python-Dev] getstate() not inherited when slots present (original) (raw)

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