mirror of
https://github.com/python/cpython.git
synced 2025-10-03 13:45:29 +00:00
bpo-33805: Improve error message of dataclasses.replace() (GH-7580)
This commit is contained in:
parent
66ecefcfe7
commit
3d70f7aef6
3 changed files with 20 additions and 0 deletions
|
@ -1173,6 +1173,9 @@ def replace(obj, **changes):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if f.name not in changes:
|
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)
|
changes[f.name] = getattr(obj, f.name)
|
||||||
|
|
||||||
# Create the new object, which calls __init__() and
|
# Create the new object, which calls __init__() and
|
||||||
|
|
|
@ -3024,6 +3024,22 @@ class TestReplace(unittest.TestCase):
|
||||||
|
|
||||||
replace(c, x=5)
|
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):
|
## def test_initvar(self):
|
||||||
## @dataclass
|
## @dataclass
|
||||||
## class C:
|
## class C:
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
Improve error message of dataclasses.replace() when an InitVar is not specified
|
Loading…
Add table
Add a link
Reference in a new issue