You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm无法推断@cache装饰的类方法返回类型,如何实现自动补全?

解决PyCharm中functools.cache装饰类方法的类型识别问题

PyCharm的类型检查工具能正确识别被@cache装饰的普通函数返回类型:

from functools import cache

class MyType:
    pass

@cache
def f() -> MyType:
    ...

v = f()  # v: MyType 类型识别正常

但对类中的方法使用@cache装饰时,类型检查会将返回值识别为Any,导致无法正常自动补全:

class C:
    @cache
    def m(self) -> MyType:
        ...

v = C().m()  # v: Any 类型识别失效

以下是几种可行的解决操作:

  • 使用typing.cast显式指定返回类型
    在调用方法时,用cast强制声明返回类型,让PyCharm能正确识别:

    from typing import cast
    
    v = cast(MyType, C().m())  # v: MyType 类型识别正常
    
  • 补充类方法的类型注解
    给装饰后的方法明确标注类型,帮助PyCharm推断:

    from functools import cache
    from typing import Callable
    
    class C:
        @cache
        def m(self) -> MyType:
            ...
        # 补充方法的类型注解
        m: Callable[[], MyType]
    
  • 改用functools.lru_cache
    由于cache是lru_cache(maxsize=None)的别名,直接使用lru_cache有时能让PyCharm的类型推断更准确:

    from functools import lru_cache
    
    class C:
        @lru_cache(maxsize=None)
        def m(self) -> MyType:
            ...
    
    v = C().m()  # 部分PyCharm版本可正确识别为MyType
    
  • 自定义类型安全的缓存装饰器
    实现一个简单的装饰器,保留原方法的类型信息:

    from functools import wraps, cache
    from typing import TypeVar, Callable
    
    T = TypeVar('T')
    
    def typed_cache(func: Callable[..., T]) -> Callable[..., T]:
        cached_func = cache(func)
        @wraps(func)
        def wrapper(*args, **kwargs) -> T:
            return cached_func(*args, **kwargs)
        return wrapper
    
    class C:
        @typed_cache
        def m(self) -> MyType:
            ...
    
    v = C().m()  # v: MyType 类型识别正常
    

内容的提问来源于stack exchange,提问作者InSync

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:07:19