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 all commits
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 @@ -3232,12 +3232,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
14 changes: 13 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6561,7 +6561,12 @@ 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 isinstance(old, Var) and is_init_only(old):
if old.has_explicit_value:
self.fail("InitVar with default value cannot be redefined", context)
elif not (
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 @@ -7575,3 +7580,10 @@ def halt(self, reason: str = ...) -> NoReturn:
return isinstance(stmt, PassStmt) or (
isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)
)


def is_init_only(node: Var) -> bool:
return (
isinstance(type := get_proper_type(node.type), Instance)
and type.type.fullname == "dataclasses.InitVar"
)
55 changes: 55 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -2476,6 +2476,61 @@ 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 testDataclassesDefaultValueInitVarWithProperty]
from dataclasses import InitVar, dataclass, field

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

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

@property # E: InitVar with default value cannot be redefined
def foo(self) -> str:
return self._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]

[case testDataclassInheritanceWorksWithExplicitOverridesAndOrdering]
# flags: --enable-error-code explicit-override
Expand Down
Loading