Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, override__getstate__() and __setstate__()

Tags:

python

I have these classes:

class Family(object):
    __slot__ = ['father', 'var1']
    def __init__(self, father, var1 = 1):
        self.father, self.var1 = father var1

class Father(object):
    __slots__ = ['var2']
    def __init__(self, var2 = ''):
        self.var2 = var2

father = Father()
family = Family(father = father)

And i want to pickle "family" object. so i need to override __getstate__ and __setstate__ "Family" and "Father" classes.

Can you show me an efficient way of doing this. (the reason why I use __slots__ is because I have lot of objects and I am trying to save memory)

like image 957
user1454592 Avatar asked Sep 27 '12 18:09

user1454592


1 Answers

__getstate__ should return a picklable object (such as a tuple) with enough information to reconstruct the instance.

__setstate__ should expect to receive the same object, and use it to reconfigure the instance.

For example:

import cPickle as pickle

class Family(object):
    __slots__ = ['father', 'var1']
    def __init__(self, father, var1 = 1):
        self.father, self.var1 = father, var1
    def __getstate__(self):
        return self.father, self.var1
    def __setstate__(self, state):
        self.father, self.var1 = state

foo = Family('father',1)
foo.var1 = 2
foo_pickled = pickle.dumps(foo)
foo2 = pickle.loads(foo_pickled)
print(repr(foo2))
# <__main__.Family object at 0xb77037ec>

print(foo2.var1)
# 2
like image 198
unutbu Avatar answered Oct 13 '22 08:10

unutbu