Skip to content

[3.8] bpo-36470: Allow dataclasses.replace() to handle InitVars with default values (GH-20867) #25201

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 5, 2021
Merged
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 @@ -1280,7 +1280,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 @@ -3252,6 +3252,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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix dataclasses with ``InitVar``\s and :func:`~dataclasses.replace()`. Patch
by Claudiu Popa.