Skip to content

Support properties with generic setters #19298

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 1 commit into from
Jun 16, 2025
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
8 changes: 7 additions & 1 deletion mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,7 +968,13 @@ def expand_and_bind_callable(
# TODO: a decorated property can result in Overloaded here.
assert isinstance(expanded, CallableType)
if var.is_settable_property and mx.is_lvalue and var.setter_type is not None:
# TODO: use check_call() to infer better type, same as for __set__().
if expanded.variables:
type_ctx = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context)
_, inferred_expanded = mx.chk.expr_checker.check_call(
expanded, [type_ctx], [ARG_POS], mx.context
)
expanded = get_proper_type(inferred_expanded)
assert isinstance(expanded, CallableType)
if not expanded.arg_types:
# This can happen when accessing invalid property from its own body,
# error will be reported elsewhere.
Expand Down
29 changes: 29 additions & 0 deletions test-data/unit/check-generics.test
Original file line number Diff line number Diff line change
Expand Up @@ -3628,3 +3628,32 @@ def draw_none(
takes_int_str_none(c2)
takes_int_str_none(c3)
[builtins fixtures/tuple.pyi]

[case testPropertyWithGenericSetter]
from typing import TypeVar

class B: ...
class C(B): ...
T = TypeVar("T", bound=B)

class Test:
@property
def foo(self) -> list[C]: ...
@foo.setter
def foo(self, val: list[T]) -> None: ...

t1: Test
t2: Test

lb: list[B]
lc: list[C]
li: list[int]

t1.foo = lb
t1.foo = lc
t1.foo = li # E: Value of type variable "T" of "foo" of "Test" cannot be "int"

t2.foo = [B()]
t2.foo = [C()]
t2.foo = [1] # E: Value of type variable "T" of "foo" of "Test" cannot be "int"
[builtins fixtures/property.pyi]