Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1249,7 +1249,7 @@ class C:
continue

if f.name not in changes:
if f._field_type is _FIELD_INITVAR:
if f._field_type is _FIELD_INITVAR and f.default is MISSING:
raise ValueError(f"InitVar {f.name!r} "
'must be specified with replace()')
changes[f.name] = getattr(obj, f.name)
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3214,6 +3214,24 @@ def __post_init__(self, y):
c = replace(c, x=3, y=5)
self.assertEqual(c.x, 15)

def test_initvar_with_default_value(self):
Comment thread
PCManticore marked this conversation as resolved.
Outdated
@dataclass
class C:
x: int
y: InitVar[int] = None
z: InitVar[int] = 42

def __post_init__(self, y, z):
if y is not None:
self.x += y
if z is not None:
self.x += z

c = C(x=1, y=10, z=1)
self.assertEqual(replace(c), C(x=12))
self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))
self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))

def test_recursive_repr(self):
@dataclass
class C:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix dataclasses with InitVars and replace(). Patch by Claudiu Popa.