@property decorator type hints

Viewed 396

Can I somehow tell mypy the type of my getter (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

Note that this is less ambitious than this related post.

1 Answers

You can use generics and annotate your functions correspondingly. So you basically define a TypeVar and annotate the function that should be decorated to return that type and also the get function to return that type.

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

Related