I have a scenario where I’ve two dataclass which share some command keys. Let’s say
JavaScript
x
6
1
@dataclass
2
class A
3
key1: str = ""
4
key2: dict = {}
5
key3: Any = ""
6
and class B
JavaScript
1
6
1
@dataclass
2
class B
3
key1: str = ""
4
key3: Any = ""
5
key4: List = []
6
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
1
5
1
# State of dataclass A while B is not initialized
2
A(key1: "key1value", Key2: {"a": "a"}, key3: [1,2])
3
# State of B should be
4
B(key1: "key1value",key3: [1,2], key4: [])
5
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
1
29
29
1
from dataclasses import dataclass, field
2
from inspect import signature
3
from typing import Any, List, Dict
4
5
def main():
6
instanceA, instanceB = A("key1value", {"a": "a"}, [1,2]), B()
7
attrsA, attrsB = signature(A).parameters, signature(B).parameters
8
9
for attr in attrsA:
10
if attr in attrsB:
11
valueA = getattr(instanceA, attr)
12
setattr(instanceB, attr, valueA)
13
14
@dataclass
15
class A:
16
key1: str = ""
17
key2: Dict[str, str] = field(default_factory=dict)
18
key3: Any = ""
19
20
@dataclass
21
class B:
22
key1: str = ""
23
key3: Any = ""
24
key4: List = field(default_factory=list)
25
26
27
if __name__ == '__main__':
28
main()
29
Instances before assign:
JavaScript
1
3
1
A(key1='key1value', key2={'a': 'a'}, key3=[1, 2])
2
B(key1='', key3='', key4=[])
3
After:
JavaScript
1
3
1
A(key1='key1value', key2={'a': 'a'}, key3=[1, 2])
2
B(key1='key1value', key3=[1, 2], key4=[])
3