如何为Python魔法__get__方法及method正确添加类型提示
为描述器类添加类型提示,让Pylance正确识别属性类型
先看这段示例代码:
class Foo: def __init__(self, method): self.method = method def __get__(self, instance, owner): if instance is None: return self return self.method(instance) class Bar: @Foo def do_something(self) -> int: return 1 Bar().do_something # 实际结果为int类型,但Pylance无法正确识别 Bar.do_something # 实际结果为Foo对象,需正确标注类型
要让Pylance像识别标准property一样,区分实例访问和类访问时的不同类型,需要借助泛型和类型变量来关联方法的输入输出类型,具体修改如下:
from typing import TypeVar, Generic, Callable, Optional, Type # 定义两个类型变量,分别关联实例类型和方法返回类型 InstanceType = TypeVar('InstanceType') ReturnType = TypeVar('ReturnType') class Foo(Generic[InstanceType, ReturnType]): method: Callable[[InstanceType], ReturnType] def __init__(self, method: Callable[[InstanceType], ReturnType]) -> None: self.method = method def __get__( self, instance: Optional[InstanceType], owner: Type[InstanceType] ) -> ReturnType | Foo[InstanceType, ReturnType]: if instance is None: return self return self.method(instance) class Bar: @Foo def do_something(self) -> int: return 1 # 此时Pylance会正确识别类型: Bar().do_something # 类型为int Bar.do_something # 类型为Foo[Bar, int]
关键说明:
- 通过
Generic[InstanceType, ReturnType]将Foo定义为泛型类,分别绑定被装饰方法的实例类型(比如Bar)和返回值类型(比如int)。 method标注为Callable[[InstanceType], ReturnType],明确它是接收一个实例参数、返回指定类型值的函数。__get__的返回值标注为ReturnType | Foo[InstanceType, ReturnType]:类访问时返回Foo自身,实例访问时返回方法的返回值,完美匹配两种访问场景的类型。
这样修改后,Pylance就能准确识别两种访问方式下的类型,和标准property的类型提示行为完全一致。
内容的提问来源于stack exchange,提问作者feiyang472
相关产品推荐
相关产品推荐

