Pickling dynamically generated classes?
When the Pickler encounters an object of a type it knows nothing about, it looks for a reduce method. Defining this method when you build your custom class using type should solve the problem of pickling.
If you provide initial args then in addition you might need to define a getnewargs method
Pickling inner classes
It's certainly a lot simpler to keep your classes unnested. As an alternative, you can use packages to group the classes together.
In any case, there is an alternate serializer named cerealizer
which I think could handle the nested classes. You would need to register the classes with it before deserialization. I've used it before when pickle
wouldn't suffice (also problems related to the classes) and it works well!
Pickle base class from derived class instance
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 Topics
Python Regex to Find a String in Double Quotes Within a String
How to Get Windows' Special Folders for Currently Logged-In User
Importerror: Cannot Import Name Numpy_Mkl
In Python, Is It Better to Use List Comprehensions or For-Each Loops
Pandas Interpolate Within a Groupby
Improve Current Implementation of a Setinterval
SQL Alchemy Orm Returning a Single Column, How to Avoid Common Post Processing
Tuple Unpacking Order Changes Values Assigned
How to Set a Proxy for Phantomjs/Ghostdriver in Python Webdriver
How to Format a Date in Jinja2
Counting Letter Frequency in a String (Python)
Time Complexity of String Concatenation in Python
How to Check for Python Version in a Program That Uses New Language Features
Changing Variable Names with Python for Loops
How to Get Millisecond and Microsecond-Resolution Timestamps in Python
How to Extract a Subset of a Colormap as a New Colormap in Matplotlib