-1

I have a class object I want to pickle with dill:

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

a = A(5)
with open('file.pkl', 'wb') as f:
    pickle.dump(a, f)

This works

I now want to make a copy like:

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

    @property
    def cast_as_b(self):
         return B(self.a)

class B(A):
    pass

a = A(5)
with open('file.pkl', 'wb') as f:
    pickle.dump(a.cast_as_b, f)

In which case I get an error

missing 2 required positional arguments

Which seems weird because it's the same class

(In this example it does work, but in my bigger example it fails, I'm not sure what the difference, problem is that I solved it, see the answer below)

Nathan
  • 3,558
  • 1
  • 18
  • 38

1 Answers1

0

The solution was that the initial class had been added:

def pickle_A(a):
    kwargs = dict(a=a.a)
    return unpickle_A, (kwargs, )

def upickle_A(kwargs):
    return A(**kwargs)
   
copyreg.pickle(A, pickle_A)

Including this exact same code also for B solved the issue

Nathan
  • 3,558
  • 1
  • 18
  • 38