Home > database >  Pickle base class from derived class instance
Pickle base class from derived class instance

Time:06-21

My base class looks like :

@dataclass
class A:
    var1: List[float]
    var2: float

and derived class looks like :

class B(A):
    def __init__(self, v1):
        super().__init__(v1, 0)

    def process():
        pass

I want a way to pickle an instance of B in a way such that only class A is required to unpickle it. I understand that python does not support upcasting but is there a way to achieve what I want? I want something like the following:

l1 = [1., 2., 4.]
obj = B(l1)
with open(filename, 'wb') as pickleFile:
    pickleFile.write(pickle.dumps((A)obj))

Followup question. something like this works but I am not sure of the consequences:

l1 = [1., 2., 4.]
obj = B(l1)
obj.__class__ = A
with open(filename, 'wb') as pickleFile:
    pickleFile.write(pickle.dumps(obj))

Any help would be appreciated. Thanks!

CodePudding user response:

You can effectively do what you want by using the module-level dataclasses.asdict() utility function to convert the B dataclass object into a dict (which is the default factory function), and then use that to create a base class instance. This isn't quite the same thing as "upcasting" the B instance into an A instance, but effect is similar.

import dataclasses
from dataclasses import dataclass
import pickle
from typing import List


@dataclass
class A:
    var1: List[float]
    var2: float

class B(A):
    def __init__(self, v1):
        super().__init__(v1, 0)

    def process(self):
        pass

    def as_A(self):
        d = dataclasses.asdict(obj)
        return A(**d)


filename = 'derived_class.pkl'
l1 = [1., 2., 4.]
obj = B(l1)
with open(filename, 'wb') as pickleFile:
    pickleFile.write(pickle.dumps(obj.as_A()))
  • Related