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

如何为static_property装饰器添加类型支持以实现正确类型推断

给静态属性装饰器添加类型支持

要让类型检查器(如mypy、Pyright)正确推断Foo.bar的类型而非Any,核心是给static_property添加泛型类型注解,让装饰器能捕获并传递目标函数的返回值类型。

修改现有类式装饰器

直接在原装饰器类中引入泛型,明确类型传递逻辑:

from typing import Generic, TypeVar, Callable

# 定义泛型变量,用于捕获getter函数的返回值类型
T = TypeVar('T')

class static_property(Generic[T]):
    def __init__(self, getter: Callable[type, T]) -> None:
        self.__getter = getter

    def __get__(self, obj: object | None, objtype: type) -> T:
        return self.__getter(objtype)

    @staticmethod
    def __call__(getter_fn: Callable[type, T]) -> 'static_property[T]':
        return static_property(getter_fn)

关键改动说明

  • 用Generic[T]让装饰器类成为泛型类,绑定返回值类型T
  • 给__init__、__call__的参数添加注解,明确getter是接收类对象(type)并返回T的函数
  • __get__方法标注返回值为T,告诉类型检查器访问该属性时的结果类型

应用示例

class Foo:
    @static_property
    def bar(cls) -> int:  # 建议用cls代替self,符合静态属性接收类的语义
        return 10

# 类型检查器会正确推断Foo.bar的类型为int
reveal_type(Foo.bar)  # 输出: Revealed type is "builtins.int"

另一种简洁实现方式

如果偏好函数式装饰器写法,也可以用嵌套类实现描述符,同样支持类型推断:

from typing import Generic, TypeVar, Callable, object

T = TypeVar('T')

def static_property(getter: Callable[type, T]) -> Generic[T]:
    class _StaticProperty(Generic[T]):
        def __get__(self, obj: object | None, objtype: type) -> T:
            return getter(objtype)
    return _StaticProperty()

注意事项

  • 原代码中@static_prop是笔误,需改为@static_property
  • 装饰的方法参数用cls更合理,因为该方法实际接收的是类本身而非实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:01:42