I have developed a system with different classes. Some classes are attributes of other classes, such as:
@dataclass
class MyFirst:
name: str
numb: float
time: pd.Series
my_second: MySecond = field(default_factory=lambda: MySecond()
@dataclass
class MySecond:
name: str
date: pd.Series
I have this structure for about 2-5 sub-classes being the attribute of another class. Now I would like to write my object:
system = my_first()
To a dictionary. I create a tuple with all my classes at first
my_classes = (MyFirst, MySecond,...)
Then, I iterated over the highest-class
dict_system = {}
for attr in dir(system):
if not attr.startswith("__") and not callable(getattr(system, attr)):
if isinstance(getattr(system, attr), (pd.Series, pd.DataFrame, float, int, str)):
dict_system[attr] = getattr(system, attr)
elif isinstance(getattr(system, attr), my_classes):
In the elif, I need him to jump again and iterate the new subclass, which would again be a dictionary, creating a nested dictionary. Finally, it would look like this:
dict_system = {
"name": "some_name",
"numb": 3,
"time": pd.Series([0,1,2,3]),
"my_second": {
"name": "second_name",
"date": pd.Series([date_1, date_2,...])
}
}
Is there a way to build this in a recursive function so I can have as many subclasses as I like, and they would appear in a nested dictionary?