Python implementation issue.
Default values are class attributes, which are shared among all instances!
Reference: https://peps.python.org/pep-0557/#mutable-default-values
So dataclasses tries to fix this...
class X:
i : int = 0
s : str = str()
l : list = []
No problem.
from dataclasses import dataclass
@dataclass
class Y:
i: int = 0
s: str = str()
l: list = []
Output: Initializing with an empty list fails for dataclass:
Traceback (most recent call last):
File "/tmp/tt", line 8, in <module>
class Y:
[...]
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'list'> for field l is not allowed: use default_factory
For normal classes you get no error, but unexpected behavior:
class X:
l : list = []
instance1 = X()
instance2 = X()
instance1.l.append("Added to instance 1 only.")
print(f'''
instance1.l: {instance1.l}
instance2.l: {instance2.l}
''')
Output
instance1.l: ['Added to instance 1 only.']
instance2.l: ['Added to instance 1 only.']
😦
For more details PEP-0557