1
import pickle

class Foo:
    x = "Cannot be pickled"

    def __init__(self, a):
        self.a = a

hello = Foo(a = 10)

with open("foo.pickle", "wb") as f:
    pickle.dump(hello, f)

with open("foo.pickle", "rb")  as f:
    world = pickle.load(f)
    print(f"world.a: {world.a}, world.x: {world.x}")

Output:

world.a: 10, world.x: Cannot be pickled

In the above code pickling and unpickling of class variables works fine for me. But in this stackoverflow link Pickle both class variables and instance variables? it says we can't pickle class variables and alternate solution are given using dill module.

Can anyone explain why its working for me?

Praburaj
  • 613
  • 8
  • 21

1 Answers1

1

Save it as one.py

import pickle

class Foo:
    x = "Cannot be pickled"

    def __init__(self, a):
        self.a = a
        
    @classmethod
    def foo_class_method(cls):
        cls.x = "can be pickled"
    

hello = Foo(a = 10)
Foo.foo_class_method()

with open("foo.pickle", "wb") as f:
    pickle.dump(hello, f)

Save this one in separate file say two.py

import pickle

class Foo:
    x = "Cannot be pickled"

    def __init__(self, a):
        self.a = a
        
    @classmethod
    def foo_class_method(cls):
        cls.x = "can be pickled"

with open("foo.pickle", "rb")  as f:
    world = pickle.load(f)
    print(f"world.a: {world.a}, world.x: {world.x}")

Output:

world.a: 10, world.x: Cannot be pickled

If you see in one.py file eventhough x value is modified in foo_class_method() but during unpickling its not reflected.

This is because the default pickle doesn't serialize the class along with the object, instead, it merely keeps a reference to the class, which is looked up upon deserialization - Answered by @juanpa.arrivillaga

Praburaj
  • 613
  • 8
  • 21