Skip to content

Commit

Permalink
propertize Callable attributes before freezing dataclasses (#12383)
Browse files Browse the repository at this point in the history
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
  • Loading branch information
uSpike and JelleZijlstra authored Mar 29, 2022
1 parent b7d74f3 commit a33d235
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
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

0 comments on commit a33d235

Please sign in to comment.