Skip to content

Commit 6ec3712

Browse files
authored
gh-119581: Add a test of InitVar with name shadowing (#119582)
1 parent 0518edc commit 6ec3712

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Lib/test/test_dataclasses/__init__.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1317,6 +1317,29 @@ def __post_init__(self, init_base, init_derived):
13171317
c = C(10, 11, 50, 51)
13181318
self.assertEqual(vars(c), {'x': 21, 'y': 101})
13191319

1320+
def test_init_var_name_shadowing(self):
1321+
# Because dataclasses rely exclusively on `__annotations__` for
1322+
# handling InitVar and `__annotations__` preserves shadowed definitions,
1323+
# you can actually shadow an InitVar with a method or property.
1324+
#
1325+
# This only works when there is no default value; `dataclasses` uses the
1326+
# actual name (which will be bound to the shadowing method) for default
1327+
# values.
1328+
@dataclass
1329+
class C:
1330+
shadowed: InitVar[int]
1331+
_shadowed: int = field(init=False)
1332+
1333+
def __post_init__(self, shadowed):
1334+
self._shadowed = shadowed * 2
1335+
1336+
@property
1337+
def shadowed(self):
1338+
return self._shadowed * 3
1339+
1340+
c = C(5)
1341+
self.assertEqual(c.shadowed, 30)
1342+
13201343
def test_default_factory(self):
13211344
# Test a factory that returns a new list.
13221345
@dataclass

0 commit comments

Comments
 (0)