Skip to content
Advertisement

populate dataclass instance from other dataclass instance

I have a scenario where I’ve two dataclass which share some command keys. Let’s say

JavaScript

and class B

JavaScript

Both of this class share some key value. Now I want to assign those common key value from class A to to class B instance.

One way I know is to convert both the class to dict object do the process and convert it back to dataclass object. But from what I know sole purpose of dataclass is to effectively store data and manage. I believe there is some better approach.

Expected Input and Output

JavaScript

Advertisement

Answer

You can use signature to get all the attributes of your class, then getattr to check if keys have the same name, and finally setattr to change the value of classB, something like this:

JavaScript

Instances before assign:

JavaScript

After:

JavaScript
Advertisement