summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2024-05-28 17:42:01 (GMT)
committerGitHub <noreply@github.com>2024-05-28 17:42:01 (GMT)
commit08636c1a7d514a4d1d555b1fa903d985b47e8875 (patch)
tree51e79f18fcb2a68f008d17c7966d82267e5dd75e
parent3af9b75df5c1fda0ae9f1869da104e90805e8467 (diff)
downloadcpython-08636c1a7d514a4d1d555b1fa903d985b47e8875.zip
cpython-08636c1a7d514a4d1d555b1fa903d985b47e8875.tar.gz
cpython-08636c1a7d514a4d1d555b1fa903d985b47e8875.tar.bz2
[3.12] gh-119581: Add a test of InitVar with name shadowing (GH-119582) (#119673)
gh-119581: Add a test of InitVar with name shadowing (GH-119582) (cherry picked from commit 6ec371223dff4da7719039e271f35a16a5b861c6) Co-authored-by: Steven Troxler <steven.troxler@gmail.com>
-rw-r--r--Lib/test/test_dataclasses/__init__.py23
1 files changed, 23 insertions, 0 deletions
diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py
index 7c91770..c059726 100644
--- a/Lib/test/test_dataclasses/__init__.py
+++ b/Lib/test/test_dataclasses/__init__.py
@@ -1317,6 +1317,29 @@ class TestCase(unittest.TestCase):
c = C(10, 11, 50, 51)
self.assertEqual(vars(c), {'x': 21, 'y': 101})
+ def test_init_var_name_shadowing(self):
+ # Because dataclasses rely exclusively on `__annotations__` for
+ # handling InitVar and `__annotations__` preserves shadowed definitions,
+ # you can actually shadow an InitVar with a method or property.
+ #
+ # This only works when there is no default value; `dataclasses` uses the
+ # actual name (which will be bound to the shadowing method) for default
+ # values.
+ @dataclass
+ class C:
+ shadowed: InitVar[int]
+ _shadowed: int = field(init=False)
+
+ def __post_init__(self, shadowed):
+ self._shadowed = shadowed * 2
+
+ @property
+ def shadowed(self):
+ return self._shadowed * 3
+
+ c = C(5)
+ self.assertEqual(c.shadowed, 30)
+
def test_default_factory(self):
# Test a factory that returns a new list.
@dataclass