Pickling slotted instances

Andrew McNamara andrewm at object-craft.com.au
Mon Sep 16 04:48:23 CEST 2002

>> Instances using __slots__ can't be pickled - is there a fundamental reason
>> why this is so, or is it simply yet to be implemented?
>See python.org/sf/520644 for a longer discussion.

I'd actually already found several discussions like that while googling
and reading python-dev archives.  But I'm still no wiser - the closest
I can come to an answer is "it's not quite trivial and therefore hasn't
been done yet".

Guido says:

    The solution space is large, and I don't want to rush it, hence the
    decision to make it fail cleanly in 2.2.1 -- that's the best I can do.

Fair enough (I'm using the CVS 2.3, btw - it can't pickle slots either).
I'm really just wondering what makes the solution space large: my
superficial understanding suggests all the necessary information is
readily available for serialising the object's state (but I can see
metaclasses make it complex).

The SF bug you quote suggests to me that one problem is that internal
machinery that uses slots assumes that slots are not pickled, and would
get upset if slotted attributes suddenly resumed their old values.

>> At first glance, a __getstate__ for a slotted class could be as simple as:
>>     def __getstate__(self):
>>         attrs = [getattr(self, attr, None) for attr in self.__slots__]
>>         return self.__slots__, attrs
>> What am I missing?
>That won't work: it won't access the slots of the base type. Also, you
>are missing a __setstate__ implementation.

Indeed. The code snippet was intended as a discussion point, rather than a
serious implementation... 8-)

Andrew McNamara, Senior Developer, Object Craft

More information about the Python-list mailing list