问题
In this pull request it looks like type hinting support for descriptors was added.
However it looks like no finalized "correct" usage example was ever posted, nor does it looks like any documentation was ever added to the typing module or to Mypy.
It looks like the correct usage is something like this:
from typing import TypeVar
T = TypeVar('T')
V = TypeVar('V')
class classproperty():
def __init__(self, getter: Callable[[Type[T], V]) -> None:
self.getter = getter
def __get__(self, instance: Optional[T], owner: Type[T]) -> V
return self.getter(owner)
def forty_two(cls: Type) -> int:
return 42
class C:
forty_two: int = classproperty(forty_two)
which seems logical, but I have no idea if that's actually the right way to do things.
Is there any documentation on this? Or complete examples that actually works on the version that was merged?
回答1:
The method described in the question seems to work for both Mypy and the PyCharm type checker.
来源:https://stackoverflow.com/questions/54413434/type-hinting-with-descriptors