Skip to content

Commit 22aee12

Browse files
committed
bpo-33805: Improve error message of dataclasses.replace()
1 parent d689f97 commit 22aee12

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

Lib/dataclasses.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1173,6 +1173,9 @@ class C:
11731173
continue
11741174

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

11781181
# Create the new object, which calls __init__() and

Lib/test/test_dataclasses.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3024,6 +3024,22 @@ class C:
30243024

30253025
replace(c, x=5)
30263026

3027+
def test_initvar_is_specified(self):
3028+
@dataclass
3029+
class C:
3030+
x: int
3031+
y: InitVar[int]
3032+
3033+
def __post_init__(self, y):
3034+
self.x *= y
3035+
3036+
c = C(1, 10)
3037+
self.assertEqual(c.x, 10)
3038+
with self.assertRaisesRegex(ValueError, r"InitVar 'y' must be "
3039+
"specified with replace()"):
3040+
replace(c, x=3)
3041+
c = replace(c, x=3, y=5)
3042+
self.assertEqual(c.x, 15)
30273043
## def test_initvar(self):
30283044
## @dataclass
30293045
## class C:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve error message of dataclasses.replace() when an InitVar is not specified

0 commit comments

Comments
 (0)