fork download
  1. import copy
  2. from dataclasses import dataclass, field, InitVar, replace
  3.  
  4. @dataclass
  5. class D:
  6. a: float = 10. # Normal attribute with a default value
  7. b: InitVar[float] = 20. # init-only attribute with a default value
  8. c: float = field(init=False) # an attribute that will be defined in __post_init__
  9.  
  10. def __post_init__(self, b):
  11. self.c = self.a + b
  12.  
  13.  
  14. def copy_dataclass(D_class, d_obj):
  15. input = {}
  16. for key, value in d_obj.__dict__.items():
  17. # If the attribute is passed to __init__
  18. if d_obj.__dataclass_fields__[key].init:
  19. input[key] = copy.deepcopy(value)
  20.  
  21. copy_d = D_class(**input)
  22.  
  23. return copy_d
  24. d1 = D(1, 2)
  25. d2 = copy_dataclass(D, d1)
  26. print(d1, d2)
Success #stdin #stdout 0.03s 10692KB
stdin
Standard input is empty
stdout
D(a=1, c=3) D(a=1, c=21.0)