Skip to content

propertize Callable attributes before freezing dataclasses #12383

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 4 commits into from
Mar 29, 2022
Merged
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
7 changes: 5 additions & 2 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ def transform(self) -> None:
)

if decorator_arguments['frozen']:
self._propertize_callables(attributes, settable=False)
self._freeze(attributes)
else:
self._propertize_callables(attributes)
Expand Down Expand Up @@ -466,7 +467,9 @@ def _freeze(self, attributes: List[DataclassAttribute]) -> None:
var._fullname = info.fullname + '.' + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)

def _propertize_callables(self, attributes: List[DataclassAttribute]) -> None:
def _propertize_callables(self,
attributes: List[DataclassAttribute],
settable: bool = True) -> None:
"""Converts all attributes with callable types to @property methods.

This avoids the typechecker getting confused and thinking that
Expand All @@ -480,7 +483,7 @@ def _propertize_callables(self, attributes: List[DataclassAttribute]) -> None:
var = attr.to_var()
var.info = info
var.is_property = True
var.is_settable_property = True
var.is_settable_property = settable
var._fullname = info.fullname + '.' + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)

Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -1537,6 +1537,22 @@ A(1)
A(a="foo") # E: Argument "a" to "A" has incompatible type "str"; expected "int"
[builtins fixtures/dataclasses.pyi]

[case testDataclassesCallableFrozen]
# flags: --python-version 3.7
from dataclasses import dataclass
from typing import Any, Callable
@dataclass(frozen=True)
class A:
a: Callable[..., None]

def func() -> None:
pass

reveal_type(A.a) # N: Revealed type is "def (*Any, **Any)"
A(a=func).a()
A(a=func).a = func # E: Property "a" defined in "A" is read-only
[builtins fixtures/dataclasses.pyi]

[case testDataclassesMultipleInheritanceWithNonDataclass]
# flags: --python-version 3.10
from dataclasses import dataclass
Expand Down