https://github.com/python/cpython/commit/6ec371223dff4da7719039e271f35a16a5b861c6
commit: 6ec371223dff4da7719039e271f35a16a5b861c6
branch: main
author: Steven Troxler <[email protected]>
committer: AlexWaygood <[email protected]>
date: 2024-05-28T18:18:57+01:00
summary:

gh-119581: Add a test of InitVar with name shadowing (#119582)

files:
M Lib/test/test_dataclasses/__init__.py

diff --git a/Lib/test/test_dataclasses/__init__.py 
b/Lib/test/test_dataclasses/__init__.py
index ea49596eaa4d96..04dd9f3265bb33 100644
--- a/Lib/test/test_dataclasses/__init__.py
+++ b/Lib/test/test_dataclasses/__init__.py
@@ -1317,6 +1317,29 @@ def __post_init__(self, init_base, init_derived):
         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

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]

Reply via email to