Skip to content

Commit 504089c

Browse files
committed
Add warning if redefined dataclass InitVar has a default value
1 parent e36a5f6 commit 504089c

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

mypy/semanal.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6211,9 +6211,11 @@ def add_symbol_table_node(
62116211
if not is_same_symbol(old, new):
62126212
if isinstance(new, (FuncDef, Decorator, OverloadedFuncDef, TypeInfo)):
62136213
self.add_redefinition(names, name, symbol)
6214-
if not (
6215-
is_init_only(old)
6216-
or (isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new))
6214+
if isinstance(old, Var) and is_init_only(old):
6215+
if old.has_explicit_value:
6216+
self.fail("InitVar with default value cannot be redefined", context)
6217+
elif not (
6218+
isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new)
62176219
):
62186220
self.name_already_defined(name, context, existing)
62196221
elif name not in self.missing_names[-1] and "*" not in self.missing_names[-1]:
@@ -7200,9 +7202,8 @@ def halt(self, reason: str = ...) -> NoReturn:
72007202
)
72017203

72027204

7203-
def is_init_only(node: SymbolNode | None) -> bool:
7205+
def is_init_only(node: Var) -> bool:
72047206
return (
7205-
isinstance(node, Var)
7206-
and isinstance(type := get_proper_type(node.type), Instance)
7207+
isinstance(type := get_proper_type(node.type), Instance)
72077208
and type.type.fullname == "dataclasses.InitVar"
72087209
)

test-data/unit/check-dataclasses.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2501,6 +2501,23 @@ test = Test("foo")
25012501
test.foo
25022502
[builtins fixtures/dataclasses.pyi]
25032503

2504+
[case testDataclassesDefaultValueInitVarWithProperty]
2505+
from dataclasses import InitVar, dataclass, field
2506+
2507+
@dataclass
2508+
class Test:
2509+
foo: InitVar[str] = "foo"
2510+
_foo: str = field(init=False)
2511+
2512+
def __post_init__(self, foo: str) -> None:
2513+
self._foo = foo
2514+
2515+
@property # E: InitVar with default value cannot be redefined
2516+
def foo(self) -> str:
2517+
return self._foo
2518+
2519+
[builtins fixtures/dataclasses.pyi]
2520+
25042521
[case testDataclassesWithProperty]
25052522
from dataclasses import dataclass
25062523

0 commit comments

Comments
 (0)