Skip to content

bpo-33805: Improve error message of dataclasses.replace() #7580

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
Jun 23, 2018
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
3 changes: 3 additions & 0 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1173,6 +1173,9 @@ class C:
continue

if f.name not in changes:
if f._field_type is _FIELD_INITVAR:
raise ValueError(f"InitVar {f.name!r} "
'must be specified with replace()')
changes[f.name] = getattr(obj, f.name)

# Create the new object, which calls __init__() and
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3024,6 +3024,22 @@ class C:

replace(c, x=5)

def test_initvar_is_specified(self):
@dataclass
class C:
x: int
y: InitVar[int]

def __post_init__(self, y):
self.x *= y

c = C(1, 10)
self.assertEqual(c.x, 10)
with self.assertRaisesRegex(ValueError, r"InitVar 'y' must be "
"specified with replace()"):
replace(c, x=3)
c = replace(c, x=3, y=5)
self.assertEqual(c.x, 15)
## def test_initvar(self):
## @dataclass
## class C:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve error message of dataclasses.replace() when an InitVar is not specified