Skip to content
Advertisement

How to persist and load all attributes of a dataclass

I want to persist all attributes of an object which is an instance of a dataclass. Then I want to load back that object from the files that I persisted.

Here it is an example that fullfills the task:

JavaScript
JavaScript

As you can see I need to repeat the same code for every attribute, what is a better way to do it?

Advertisement

Answer

In the save method it use self.__dict__. That contains all attribute names and values as a dictionary. Load is a classmethod so there is no __dict__ at that stage. However, cls.__annotations__ contains attribute names and types, still stored in a dictionary.

Here it is the end result:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement