How to pickle a subclass of tuple?

  • Thread starter Christos TZOTZIOY Georgiou
  • Start date
C

Christos TZOTZIOY Georgiou

__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?
 
S

Shalabh Chaturvedi

Christos said:
__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?
 
C

Christos TZOTZIOY Georgiou

Why do you need to do this i.e. redefine __getstate__() and __setstate__()?

Doesn't just pickling instances of your class work?

33

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.
 
G

Greg Chapman

__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?

You'll probably need to use some of the extended pickle protocol hooks
documented here:

http://www.python.org/peps/pep-0307.html

In particular, you can give your subclass a __reduce__ implementation, which
pretty much gives you complete control over how it is pickled and unpickled.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top