如何访问使用 @property 装饰器注释的方法的类型提示?
通常,这是非常简单的:
>>> class Foo:
... def bar(self) -> str:
... pass
...
>>> import typing
>>> typing.get_type_hints(Foo.bar)
{'return': <class 'str'>}
但是一旦bar
被@property
注解,做成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__)
{}
最佳答案
__get__
不是实际函数,而是它的包装器:
>>> Foo.bar.__get__
<method-wrapper '__get__' of property object at 0x11d6f3b88>
要访问该函数,您可以使用 property.fget
:
>>> Foo.bar.fget
<function __main__.Foo.bar>
当然还有注释:
>>> typing.get_type_hints(Foo.bar.fget)
{'return': str}
这不是很明显或无法发现。 IIRC,这在 python-ideas 的某个时刻出现了——对于 Mypy 或其他外部静态分析器来说,获取 property
的注释相对容易,但对于程序内部的代码则不然——但我假设没有人想出了一个很好的答案,否则它就会被实现(或者至少在 PEP 526 中讨论过)。
关于python - 用@property 注释的方法的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480716/