How to pickle a subclass of tuple?

Christos TZOTZIOY Georgiou tzot at
Fri Jun 4 10:44:19 CEST 2004

On Thu, 03 Jun 2004 17:52:45 -0700, rumours say that Shalabh Chaturvedi
<shalabh at> might have written:

>Christos TZOTZIOY Georgiou wrote:
>> __getstate__ is easy:
>> def __getstate__(self):
>>     return tuple(self)
>> but even
>> def __getstate__(self):
>>     return self
>> seems to work, as far as Pickle.dump is concerned.  The problem is, how
>> one writes a __setstate__ for an immutable class?
>Why do you need to do this i.e. redefine __getstate__() and __setstate__()?
>Doesn't just pickling instances of your class work?
> >>> class T(tuple):pass
> >>> t = T((1,2))
> >>> t.a = 33
> >>> import pickle
> >>> x = pickle.loads(pickle.dumps(t))
> >>> x
>(1, 2)
> >>> x.a

Oh, yeah, I forgot to mention that I also define __slots__ to avoid
having a dictionary; I do that because I need to create *really* lots of
instances, and the memory usage became prohibiting for the specific
computer I want this to run (a firewall).

It's data about various of ip addresses related to an anti-spam program.
I want to cache results to avoid running DNS requests every time.

So, apart from advice on how to circumvent this for my specific problem
(eg, run on another computer, don't base on tuple etc) since I already
have circumvented it, I would still like to find out if it is possible
or not to pickle a tuple-based class with __slots__ defined.
TZOTZIOY, I speak England very best,
"I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses

More information about the Python-list mailing list