Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 28, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

@property
def shadowed(self):
return self._shadowed

c = C(5)
self.assertEqual(c.shadowed, 5)

def test_default_factory(self):
# Test a factory that returns a new list.
@dataclass
Expand Down
Loading