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

如何为custom_property函数添加注解,实现不同场景的正确类型提示?

自定义Property的上下文感知类型注解解决方案

你遇到的问题是custom_property函数需要根据使用上下文返回不同的类型注解:

  • 在类内部作为类属性赋值时,类型检查器应提示实例访问该属性时的实际类型(如传入int时,实例属性类型为int)
  • 在模块级直接调用时,类型检查器应提示返回CustomProperty实例,以便调用其自定义方法a_function()

之前尝试Union[_B, CustomProperty]会得到混合类型,无法满足两种场景的精确提示需求。

解决方案

使用typing.overload为函数定义多个类型签名,让类型检查器根据上下文自动推断正确的返回类型。核心逻辑是通过重载区分两种使用场景:

from typing import TypeVar, overload, Any

_B = TypeVar("_B")

class CustomProperty(property):
    def a_function(self) -> None:
        # 补充self参数,确保是实例方法
        ...

@overload
def custom_property(type: _B) -> property[_B]:
    ...

@overload
def custom_property(type: _B) -> CustomProperty:
    ...

def custom_property(type: Any) -> CustomProperty:
    return CustomProperty(type)

# 模块级调用:类型检查器提示返回CustomProperty,可正常调用a_function()
custom_property(int).a_function()

class ClassWithCustomProperty:
    # 类内赋值:类型检查器会将实例的property_holder属性推断为int类型
    property_holder = custom_property(int)

# 验证实例属性类型(以mypy为例)
obj = ClassWithCustomProperty()
reveal_type(obj.property_holder)  # 输出:Revealed type is "builtins.int"

关键说明

  1. 重载签名的作用:

    • 第一个重载-> property[_B]:告诉类型检查器,当函数被用作类属性的property定义时,实例访问该属性会得到_B类型
    • 第二个重载-> CustomProperty:对应直接调用场景,允许调用CustomProperty的自定义方法
  2. 兼容性保障:
    CustomProperty继承自标准库的property,因此返回CustomProperty实例完全兼容property[_B]的类型签名,不会引发运行时错误

  3. 细节修正:
    原代码中CustomProperty.a_function缺少self参数,必须补充才能作为实例方法调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:03:30