E pur si muove

On using .__getstate__()

Tuesday, December 01, 2009

Do not, I repeat, do not define .__getstate__() idly.

Thank you very much

Tuesday, December 01, 2009 | Labels: |


Unknown said...

It's seldomly needed, only in case picking of the class does not work should it be used (which is possible with circular references inside the classes __dict__ I think, but didn't check). One sharp edge to get cut on is that deepcopy is afected by it too (but consider using __deepcopy__ if that's your problem/aim).

If you do need to define it because of problems (and not just because someone thinks it's cute or to save space in copies or some other silly reason) then be very careful to write it in such a way that it excludes unwanted items from the state, rather then including the wanted items. Otherwise it is very easy to lead to subtle and hard to find bugs, certainly if the __getstate__ is defined in a base class.

Anonymous said...

For anyone finding this via searching, "picking" should say "pickling" in Floris' response above.

A pretty reliable way to get a working __getstate__ (and __setstate__) is to store all of the object's persistent state in a dictionary (probably called self._state) and return that from __getstate__ and restore it in __setstate__. To know what to put in it (what counts as "persistent state"), it should be all the stuff needed to construct a functionally equivalent object (since that's the purpose of it).

New comments are not allowed.

Subscribe to: Post Comments (Atom)