使用描述符进行类型提示

sha*_*ker 8 python type-hinting python-3.x python-descriptors mypy

在这个拉取请求中,似乎添加了对描述符的类型提示支持。

但是,似乎从未发布过最终的“正确”使用示例,也似乎从未将任何文档添加到typing模块或Mypy 中。

它看起来像的正确用法是像这样:

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)
Run Code Online (Sandbox Code Playgroud)

这似乎合乎逻辑,但我不知道这是否真的是正确的做事方式。

有没有这方面的文件?或者实际适用于合并版本的完整示例?

ser*_*iy1 4

经过一段时间的努力解决这个问题,当您搜索“类型提示描述符”时,此页面是最重要的结果,我想分享一个完全满足 mypy 和 Pyright 静态类型检查器的解决方案,与 python 3.6 兼容并且不兼容继承自property

from typing import Callable, Generic, Type, TypeVar, overload, Union


Instance = TypeVar('Instance')
Value = TypeVar('Value')
Attribute = TypeVar('Attribute')


class Descriptor(Generic[Instance, Attribute, Value]):
    def __init__(self, method: Callable[[Instance, Attribute], Value]):
        """ Called on initialisation of descriptor """

    @overload
    def __get__(self, instance: None, owner: Type[Instance]) -> 'Descriptor':
        """ Called when an attribute is accessed via class not an instance """

    @overload
    def __get__(self, instance: Instance, owner: Type[Instance]) -> Value:
        """ Called when an attribute is accessed on an instance variable """

    def __get__(self, instance: Union[Instance, None], owner: Type[Instance]) -> Union[Value, 'Descriptor']:
        """ Full implementation is declared here """
        ...

    def __set__(self, instance: Instance, value: Value):
        """ Called when setting a value."""
        
Run Code Online (Sandbox Code Playgroud)