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
16 changes: 16 additions & 0 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
MypyFile,
NameExpr,
OverloadedFuncDef,
RefExpr,
SymbolTable,
TempNode,
TypeAlias,
Expand Down Expand Up @@ -1304,6 +1305,21 @@ def analyze_class_attribute_access(
result = t
# __set__ is not called on class objects.
if not mx.is_lvalue:
if is_decorated and any(
isinstance(d, RefExpr) and d.fullname == "functools.cached_property"
for d in cast(Decorator, node.node).original_decorators
):
# Accessing a functools.cached_property through the class object
# returns the descriptor itself, not the getter. At runtime the
# value is a ``cached_property`` instance (with attributes like
# ``attrname`` and ``func``), which typeshed models via
# ``__get__(self, instance: None, ...) -> Self``. (#21825)
getter_type = get_proper_type(t)
if isinstance(getter_type, CallableType):
cached_property = lookup_stdlib_typeinfo(
"functools.cached_property", modules_state.modules
)
result = Instance(cached_property, [getter_type.ret_type])
result = analyze_descriptor_access(result, mx)

return apply_class_attr_hook(mx, hook, result)
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-functools.test
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,22 @@ _T = TypeVar('_T')
class cached_property(Generic[_T]): ...
[builtins fixtures/property.pyi]

[case testCachedPropertyClassAccess]
# https://github.com/python/mypy/issues/21825
from functools import cached_property

class A:
@cached_property
def value(self) -> int:
return 1

reveal_type(A.value) # N: Revealed type is "functools.cached_property[builtins.int]"

# The descriptor instance is returned, so its attributes are accessible.
x: str | None = A.value.attrname
y: int = A.value.func(A())
[builtins fixtures/property.pyi]

[case testTotalOrderingWithForwardReference]
from typing import Generic, Any, TypeVar
import functools
Expand Down
Loading