diff options
| author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2018-06-23 15:04:01 (GMT) |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2018-06-23 15:04:01 (GMT) |
| commit | bbef7abe922edadc7a1679c19d6053240bf600d5 (patch) | |
| tree | 12ef3900638587c3aedab02dd2b6a0065bdf0d6d | |
| parent | efc6bf66a58e96c12116d65984ac69b0f36f85de (diff) | |
| download | cpython-bbef7abe922edadc7a1679c19d6053240bf600d5.zip cpython-bbef7abe922edadc7a1679c19d6053240bf600d5.tar.gz cpython-bbef7abe922edadc7a1679c19d6053240bf600d5.tar.bz2 | |
bpo-33805: Improve error message of dataclasses.replace() (GH-7580)
(cherry picked from commit 3d70f7aef614c396f516b5fccedeebe98598714d)
Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>
| -rw-r--r-- | Lib/dataclasses.py | 3 | ||||
| -rwxr-xr-x | Lib/test/test_dataclasses.py | 16 | ||||
| -rw-r--r-- | Misc/NEWS.d/next/Library/2018-06-10-15-14-17.bpo-33805.5LAz5a.rst | 1 |
3 files changed, 20 insertions, 0 deletions
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index 96bf6e1..ad7bf0f 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -1173,6 +1173,9 @@ def replace(obj, **changes): 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 diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py index 9297931..d9556c7 100755 --- a/Lib/test/test_dataclasses.py +++ b/Lib/test/test_dataclasses.py @@ -3024,6 +3024,22 @@ class TestReplace(unittest.TestCase): 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: diff --git a/Misc/NEWS.d/next/Library/2018-06-10-15-14-17.bpo-33805.5LAz5a.rst b/Misc/NEWS.d/next/Library/2018-06-10-15-14-17.bpo-33805.5LAz5a.rst new file mode 100644 index 0000000..74bcf6d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-06-10-15-14-17.bpo-33805.5LAz5a.rst @@ -0,0 +1 @@ +Improve error message of dataclasses.replace() when an InitVar is not specified |
