@property 装饰器类型提示

Ore*_*lom 3 python types python-decorators mypy

我能以某种方式告诉我的吸气剂 ( )mypy的类型吗?salary

from typing import Any
class MyProperty:
    def __init__(self, getter) -> None:
        self.getter = getter

    def __get__(self, obj, objtype=None) -> Any:
        return self.getter(obj)

class Person:
    def __init__(self) -> None:
        self.x = 7400.5

    @MyProperty
    def salary(self) -> float:
        return self.x

def check(something: str) -> None:
    # should issue: ... incompatible type float; expected str
    pass

p = Person()
check(p.salary) # <----- Success: no issues found in 1 source file
Run Code Online (Sandbox Code Playgroud)

请注意,这没有相关帖子那么雄心勃勃。

Sim*_*awe 7

您可以使用泛型并相应地注释您的函数。因此,您基本上定义了一个 TypeVar 并注释了应该修饰以返回该类型的函数以及返回该类型的get函数。

from typing import Any, Callable, TypeVar, Generic
T = TypeVar("T")

class MyProperty(Generic[T]):
    def __init__(self, getter: Callable[[Any], T]) -> None:
        self.getter = getter

    def __get__(self, obj, objtype=None) -> T:
        return self.getter(obj)

class Person:
    def __init__(self) -> None:
        self.x = 7400.5

    @MyProperty
    def salary(self) -> float:
        return self.x

Run Code Online (Sandbox Code Playgroud)