pickling class instances with __slots__

A

Alex

I would greatly appreciate an advice on the following matter that was
very much discussed circa 2002 but in all this discussion I could not
find the final answer with a code example. Neither I can find it in
Python documentation.


I have a series of new classes with child-parent relationship and each
has unique __slots__. They don't have __dict__ . I need to be able to
pickle and unpickle them. As far as I could understand, I need to
provide __getstate__ and __setstate__ methods for each class. Is
there a universally accepted code for each method? If so, what is it?
If there is no standard, what works?


TIA


Alex
 
A

Alex Martelli

Alex said:
I have a series of new classes with child-parent relationship and each
has unique __slots__. They don't have __dict__ . I need to be able to
pickle and unpickle them. As far as I could understand, I need to
provide __getstate__ and __setstate__ methods for each class. Is
Right.

there a universally accepted code for each method? If so, what is it?
If there is no standard, what works?

Lots of things work, the simplest is something like:
.... __slots__ = 'a', 'b', 'c'
.... def __getstate__(self): return self.a, self.b, self.c
.... def __setstate__(self, tup): self.a, self.b, self.c = tup

(plus presumably other methods, but those don't matter for pickle).


Alex
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top