Skip to content

Commit 7522067

Browse files
authored
bpo-36470: Allow dataclasses.replace() to handle InitVars with default values (GH-20867)
Co-Authored-By: Claudiu Popa <[email protected]> Automerge-Triggered-By: GH:ericvsmith
1 parent 14829b0 commit 7522067

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Lib/dataclasses.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1300,7 +1300,7 @@ class C:
13001300
continue
13011301

13021302
if f.name not in changes:
1303-
if f._field_type is _FIELD_INITVAR:
1303+
if f._field_type is _FIELD_INITVAR and f.default is MISSING:
13041304
raise ValueError(f"InitVar {f.name!r} "
13051305
'must be specified with replace()')
13061306
changes[f.name] = getattr(obj, f.name)

Lib/test/test_dataclasses.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3251,6 +3251,24 @@ def __post_init__(self, y):
32513251
c = replace(c, x=3, y=5)
32523252
self.assertEqual(c.x, 15)
32533253

3254+
def test_initvar_with_default_value(self):
3255+
@dataclass
3256+
class C:
3257+
x: int
3258+
y: InitVar[int] = None
3259+
z: InitVar[int] = 42
3260+
3261+
def __post_init__(self, y, z):
3262+
if y is not None:
3263+
self.x += y
3264+
if z is not None:
3265+
self.x += z
3266+
3267+
c = C(x=1, y=10, z=1)
3268+
self.assertEqual(replace(c), C(x=12))
3269+
self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))
3270+
self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))
3271+
32543272
def test_recursive_repr(self):
32553273
@dataclass
32563274
class C:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix dataclasses with ``InitVar``\s and :func:`~dataclasses.replace()`. Patch
2+
by Claudiu Popa.

0 commit comments

Comments
 (0)