Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pickle both class variables and instance variables?

Tags:

python

pickle

The pickle documentation states that "when class instances are pickled, their class’s data are not pickled along with them. Only the instance data are pickled." Can anyone provide a recipe for including class variables as well as instance variables when pickling and unpickling?

like image 330
rmodrak Avatar asked Mar 19 '23 04:03

rmodrak


1 Answers

Use dill instead of pickle, and code exactly how you probably have done already.

>>> class A(object):
...   y = 1
...   x = 0
...   def __call__(self, x):
...     self.x = x
...     return self.x + self.y
... 
>>> b = A()
>>> b.y = 4
>>> b(2)
6
>>> b.z = 5
>>> import dill
>>> _b = dill.dumps(b)
>>> b_ = dill.loads(_b)
>>> 
>>> b_.z
5
>>> b_.x
2
>>> b_.y
4
>>>
>>> A.y = 100
>>> c = A()
>>> _c = dill.dumps(c)
>>> c_ = dill.loads(_c)
>>> c_.y
100
like image 200
Mike McKerns Avatar answered Mar 26 '23 01:03

Mike McKerns