使用@property注释的方法的类型提示

asp*_*asp 7 python python-3.x

如何访问使用@property装饰器注释的方法的类型提示?

通常,这非常简单:

>>> class Foo:
...     def bar(self) -> str:
...             pass
... 
>>> import typing
>>> typing.get_type_hints(Foo.bar)
{'return': <class 'str'>}
Run Code Online (Sandbox Code Playgroud)

但是一旦bar被注释@property并制作成属性对象,它就不明显了:

>>> class Foo:
...     @property
...     def bar(self) -> str:
...             pass
... 
>>> import typing
>>> typing.get_type_hints(Foo.bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 1527, in get_type_hints
    'or function.'.format(obj))
TypeError: <property object at 0x1050fcc28> is not a module, class, method, or function.
>>> typing.get_type_hints(Foo.bar.__get__)
{}
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 5

__get__没有实际功能,但它周围的包装:

>>> Foo.bar.__get__
<method-wrapper '__get__' of property object at 0x11d6f3b88>
Run Code Online (Sandbox Code Playgroud)

要使用此功能,请使用property.fget

>>> Foo.bar.fget
<function __main__.Foo.bar>
Run Code Online (Sandbox Code Playgroud)

当然有注释:

>>> typing.get_type_hints(Foo.bar.fget)
{'return': str}
Run Code Online (Sandbox Code Playgroud)

这不是完全明显或不可发现的。IIRC,这是在python-ideas上的某个时候出现的-Mypy或其他外部静态分析器相对容易获取a的批注property,而对于程序内部的代码则相对不容易,但是我认为没有人能给出一个好的答案,或者它会被实施(或至少在PEP 526中讨论过)。