Dataclasses and mutable default factories [ref]
Problem
- Define and create a dataclass point with integer coordinates
2 and 3.
- Define a recursive dataclass node with an independently created children list.
- Append a child to one node and verify another node stays childless.
- Demonstrate shared state caused by a regular constructor's mutable default list.
Python solution
from dataclasses import dataclass, field
@dataclass
class Point:
x: int
y: int
Point(2, 3) # Point(x=2, y=3)
@dataclass
class NaryNode:
val: str
children: list["NaryNode"] = field(default_factory=list)
a, b = NaryNode("a"), NaryNode("b")
(a.children, b.children) # ([], [])
a.children.append(NaryNode("child"))
(a.children, b.children)
# ([NaryNode(val='child', children=[])], [])
class Unsafe:
def __init__(self, values=[]):
self.values = values
x, y = Unsafe(), Unsafe()
x.values.append(1)
(x.values, y.values) # ([1], [1])
Links