带描述符的类型提示 [英] Type hinting with descriptors

查看:80
本文介绍了带描述符的类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此提取请求中,它似乎添加了对描述符的类型提示支持.

In this pull request it looks like type hinting support for descriptors was added.

但是似乎没有发布任何最终的正确"用法示例,也似乎没有任何文档添加到 Mypy .

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.

看起来的正确用法类似于:

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?

推荐答案

问题中描述的方法似乎对Mypy和PyCharm类型检查器均适用.

The method described in the question seems to work for both Mypy and the PyCharm type checker.

这篇关于带描述符的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆