The default values in constructors for c1 and c2 should produce new instance variables for b and b. Instead, it looks like c1.a and c2.a are referencing the same variable. Is @dataclass creating a class variable? That does not seem to be consistent with the intended functionality, and I cannot find anything about class variables in the documentation. So, I think this is a bug. Can someone explain to me how to fix it? Should I report it as a bug on the python tracker?
I know this issue must be related to the way python passes objects by reference and built-in types by value since the b attribute (which is just a float) shows the expected/desired behavior while the a attribute (which is a user-defined object) is just a reference.
Thanks!
Code:
from dataclasses import dataclass
@dataclass
class VS:
v: float # value
s: float # scale factor
def scaled_value(self):
return self.v*self.s
@dataclass
class Container:
a: VS = VS(1, 1)
b: float = 1
c1 = Container()
c2 = Container()
print(c1)
print(c2)
c1.a.v = -999
c1.b = -999
print(c1)
print(c2)
Ouputs:
Container(a=VS(v=1, s=1), b=1)
Container(a=VS(v=1, s=1), b=1)
Container(a=VS(v=-999, s=1), b=-999)
Container(a=VS(v=-999, s=1), b=1)