Search code examples
pythonpickle

Pickle both class variables and instance variables?


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?


Solution

  • 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