Skip to content
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

Fix error on instance property and init-only variable with the same name in a dataclass #17219

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
18 changes: 12 additions & 6 deletions mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3165,12 +3165,18 @@ def get_method(self, name: str) -> FuncBase | Decorator | None:
for cls in self.mro:
if name in cls.names:
node = cls.names[name].node
if isinstance(node, FuncBase):
return node
elif isinstance(node, Decorator): # Two `if`s make `mypyc` happy
return node
else:
return None
elif possible_redefinitions := sorted(
[n for n in cls.names.keys() if n.startswith(f"{name}-redefinition")]
):
node = cls.names[possible_redefinitions[-1]].node
Comment on lines 3233 to +3238
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regardless of what we decide to do about dataclasses that redefine InitVar fields, this seems like it might be a good change.

In general, validating that there aren't redefinitions (which is happening in semanal) seems like it should be independent of getting the appropriate value for a name; when dealing with dependencies, using the last-defined value for a name seems like a good thing.

I wonder if it would be worth pulling into a helper function, and using not just for methods but other attributes as well?

else:
continue
if isinstance(node, FuncBase):
return node
elif isinstance(node, Decorator): # Two `if`s make `mypyc` happy
return node
else:
return None
return None

def calculate_metaclass_type(self) -> mypy.types.Instance | None:
Expand Down
13 changes: 12 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6211,7 +6211,10 @@ def add_symbol_table_node(
if not is_same_symbol(old, new):
if isinstance(new, (FuncDef, Decorator, OverloadedFuncDef, TypeInfo)):
self.add_redefinition(names, name, symbol)
if not (isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new)):
if not (
is_init_only(old)
or (isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new))
):
self.name_already_defined(name, context, existing)
elif name not in self.missing_names[-1] and "*" not in self.missing_names[-1]:
names[name] = symbol
Expand Down Expand Up @@ -7195,3 +7198,11 @@ def halt(self, reason: str = ...) -> NoReturn:
return isinstance(stmt, PassStmt) or (
isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)
)


def is_init_only(node: SymbolNode | None) -> bool:
return (
isinstance(node, Var)
and isinstance(type := get_proper_type(node.type), Instance)
and type.type.fullname == "dataclasses.InitVar"
)
39 changes: 39 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -2475,3 +2475,42 @@ class Base:
class Child(Base):
y: int
[builtins fixtures/dataclasses.pyi]

[case testDataclassesInitVarsWithProperty]
from dataclasses import InitVar, dataclass, field

@dataclass
class Test:
foo: InitVar[str]
_foo: str = field(init=False)

def __post_init__(self, foo: str) -> None:
self._foo = foo

@property
def foo(self) -> str:
return self._foo

@foo.setter
def foo(self, value: str) -> None:
self._foo = value

reveal_type(Test) # N: Revealed type is "def (foo: builtins.str) -> __main__.Test"
test = Test(42) # E: Argument 1 to "Test" has incompatible type "int"; expected "str"
test = Test("foo")
test.foo
[builtins fixtures/dataclasses.pyi]

[case testDataclassesWithProperty]
from dataclasses import dataclass

@dataclass
class Test:
@property
def foo(self) -> str:
return "a"

@foo.setter
def foo(self, value: str) -> None:
pass
[builtins fixtures/dataclasses.pyi]
Loading