Skip to content
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
72 changes: 71 additions & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1504,6 +1504,68 @@ def find_member(
return result


def bind_descriptor_access_simple(member_type: Type, subtype: Type) -> Type | None:
"""Bind a descriptor attribute access without a type checker.

find_member_simple() is used before type checking (e.g. by semanal_typeargs
when validating type variable bounds), so it cannot use the full descriptor
binding logic from checkmember.py, which needs a type checker. Without this,
a class attribute declared with a descriptor type (e.g. ``m: Desc``) is
treated as having the descriptor type itself, so protocol checks involving
such members fail, and the (wrong) negative result is cached and reused by
later, accurate checks. See https://github.com/python/mypy/issues/22549.

Return the type of the attribute after binding ``__get__`` for an instance
access, or None if the descriptor cannot be bound reliably, in which case
the caller should fall back to the unbound descriptor type.
"""
proper = get_proper_type(member_type)
if isinstance(proper, UnionType):
bound_items = []
for item in proper.items:
bound = bind_descriptor_access_simple(item, subtype)
bound_items.append(bound if bound is not None else item)
return mypy.typeops.make_simplified_union(bound_items)
if not isinstance(proper, Instance):
return None
if not proper.type.has_readable_member("__get__"):
return None
dunder_get = proper.type.get_method("__get__")
if dunder_get is None:
return None
if isinstance(dunder_get, Decorator):
get_type = find_node_type(dunder_get.var, proper, proper)
else:
get_type = find_node_type(dunder_get, proper, proper)
get_type = get_proper_type(get_type)
if isinstance(get_type, Overloaded):
# Select the overload that applies to an instance access: the first
# argument is the instance being accessed. Overloads taking None
# apply to class accesses instead.
candidates = [
item
for item in get_type.items
if len(item.arg_types) >= 1
and not isinstance(get_proper_type(item.arg_types[0]), NoneType)
]
if len(candidates) != 1:
return None
get_type = candidates[0]
if not isinstance(get_type, CallableType):
return None
if len(get_type.arg_types) < 1:
return None
if not is_subtype(subtype, get_type.arg_types[0]):
# The descriptor only accepts instances of some other type.
return None
ret = get_type.ret_type
# Expand Self in the return type to the descriptor instance.
self_ids = {tv.id for tv in mypy.typeops.get_all_type_vars(ret) if tv.id.is_self()}
if self_ids:
ret = expand_type(ret, {tv_id: proper for tv_id in self_ids})
return ret


def find_member_simple(
name: str,
itype: Instance,
Expand Down Expand Up @@ -1537,7 +1599,15 @@ def find_member_simple(
node = info.get(name)
v = node.node if node else None
if isinstance(v, Var):
return find_node_type(v, itype, subtype, class_obj=class_obj)
member_type = find_node_type(v, itype, subtype, class_obj=class_obj)
if not class_obj and not is_lvalue:
# Bind descriptors, so that protocol checks before type checking
# (e.g. in semanal_typeargs) see the bound member type, not the
# descriptor type itself. See #22549.
bound = bind_descriptor_access_simple(member_type, subtype)
if bound is not None:
return bound
return member_type
if (
not v
and name not in ["__getattr__", "__setattr__", "__getattribute__"]
Expand Down
67 changes: 67 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -4615,6 +4615,73 @@ z: HasInt = C # E: Incompatible types in assignment (expression has type "type[
# N: Following member(s) of "C" have conflicts: \
# N: attr: expected "int", got "Desc"

[case testProtocolDescriptorTypeArgumentBound22549]
# A class attribute declared with a descriptor type implements a protocol
# via the descriptor's __get__ return type. Checking a type argument bound
# against such a protocol must use the bound member type, not the descriptor
# type itself. See https://github.com/python/mypy/issues/22549
from typing import Generic, Protocol, Self, TypeVar, overload

T = TypeVar("T", bound="P")


class Desc:
@overload
def __get__(self, obj: None, owner: type) -> Self: ...
@overload
def __get__(self, obj: object, owner: type) -> int: ...
def __get__(self, obj: object, owner: type) -> Self | int: ...


class P(Protocol):
@property
def m(self) -> int: ...


class Box(Generic[T]): ...


class C:
m: Desc = Desc()


A = Box[C]

x: P = C()
[builtins fixtures/property.pyi]

[case testProtocolDescriptorTypeArgumentBoundBad22549]
# The bound check must still fail when the descriptor's __get__ return type
# is genuinely incompatible with the protocol.
from typing import Generic, Protocol, TypeVar

T = TypeVar("T", bound="P")


class BadDesc:
def __get__(self, obj: object, owner: type) -> str: ...


class P(Protocol):
@property
def m(self) -> int: ...


class Box(Generic[T]): ...


class D:
m: BadDesc = BadDesc()


A = Box[D] # E: Value of type variable "T" of "Box" cannot be "D" \
# E: Type argument "D" of "Box" must be a subtype of "P"

x: P = D() # E: Incompatible types in assignment (expression has type "D", variable has type "P") \
# N: Following member(s) of "D" have conflicts: \
# N: m: expected "int", got "str"
[builtins fixtures/property.pyi]

[case testProtocolErrorReportingNoDuplicates]
from typing import Callable, Protocol, TypeVar

Expand Down
32 changes: 32 additions & 0 deletions test-data/unit/check-python312.test
Original file line number Diff line number Diff line change
Expand Up @@ -2469,3 +2469,35 @@ reveal_type(a[0]) # N: Revealed type is "tuple[builtins.int, builtins.str]"
reveal_type(a[1]) # N: Revealed type is "tuple[builtins.int, builtins.str]"
reveal_type(a[2]) # N: Revealed type is "builtins.tuple[Any, ...]"
[builtins fixtures/tuple.pyi]

[case testProtocolDescriptorTypeStatement22549]
# A `type` statement must not produce a false positive when a type argument
# bound is a protocol implemented via a descriptor, and the check must not
# poison later, accurate checks. See https://github.com/python/mypy/issues/22549
from typing import Protocol, Self, overload


class Desc:
@overload
def __get__(self, obj: None, owner: type) -> Self: ...
@overload
def __get__(self, obj: object, owner: type) -> int: ...
def __get__(self, obj: object, owner: type) -> Self | int: ...


class P(Protocol):
@property
def m(self) -> int: ...


class Box[T: P]: ...


class C:
m: Desc = Desc()


type A = Box[C] | int

x: P = C()
[builtins fixtures/property.pyi]
Loading