From 0a8431dab9d5a10e4ae23a0d24ca1b138a823450 Mon Sep 17 00:00:00 2001 From: Steven Troxler Date: Sun, 26 May 2024 09:26:46 -0700 Subject: [PATCH] [gh-119581] Add a test of InitVar with name shadowing As originally discussed in https://github.com/python/mypy/pull/17219, MyPy has had a false-positive bug report because it errors when a dataclass has methods that shadow an `InitVar` field. It is actually a bit surprising that this works, it turns out that `__annotations__` "remembers" field assignments even if the bound names are later overwritten by methods; it will *not* work to provide a default value. There have been multiple bug reports on MyPy so we know people are actually relying on this in practice; most likely it comes up when a dataclass wants to take a "raw" value as an InitVar and transform it somehow in `__post_init__` into a different value before assigning it to a field; in that case they may choose to make the actual field private and provide a property for access. I currently provide a test of the happy path where there is no default value provided, but no tests of the behavior when no default is provided (in which case the property will override the default) and no documentation (because I'm not sure we want to consider this behavior officially supported). The main goal is to have a regression test since it would be easy for a refactor to break this. --- Lib/test/test_dataclasses/__init__.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index ea49596eaa4d969..4917373039ea9d9 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 + + @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