Type hinting with descriptors

心已入冬 提交于 2019-12-06 06:39:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!