Skip to content

Commit

Permalink
bpo-36470: Allow dataclasses.replace() to handle InitVars with defaul…
Browse files Browse the repository at this point in the history
…t values (GH-20867)

Co-Authored-By: Claudiu Popa <pcmanticore@gmail.com>

Automerge-Triggered-By: GH:ericvsmith
  • Loading branch information
ZackerySpytz committed Apr 5, 2021
1 parent 14829b0 commit 7522067
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Lib/dataclasses.py
Expand Up @@ -1300,7 +1300,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
Expand Up @@ -3251,6 +3251,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):
@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
@@ -0,0 +1,2 @@
Fix dataclasses with ``InitVar``\s and :func:`~dataclasses.replace()`. Patch
by Claudiu Popa.

0 comments on commit 7522067

Please sign in to comment.