[英]type hints for method annotated with @property
How do you access type hints for methods annotated with the @property decorator? 如何访问使用@property装饰器注释的方法的类型提示?
Normally, this is very straightforward: 通常,这非常简单:
>>> class Foo:
... def bar(self) -> str:
... pass
...
>>> import typing
>>> typing.get_type_hints(Foo.bar)
{'return': <class 'str'>}
But once bar
is annotated with @property
and made into a property object, it's not obvious: 但是一旦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__)
{}
The __get__
isn't the actual function, but a wrapper around it: __get__
不是实际的函数,而是它周围的包装器:
>>> Foo.bar.__get__
<method-wrapper '__get__' of property object at 0x11d6f3b88>
To access the function, you use property.fget
: 要访问该函数,请使用property.fget
:
>>> Foo.bar.fget
<function __main__.Foo.bar>
And of course that has the annotations: 当然,这有注释:
>>> typing.get_type_hints(Foo.bar.fget)
{'return': str}
That isn't exactly obvious or discoverable. 这不是很明显或可发现。 IIRC, this came up at some point on python-ideas—it's relatively easy for Mypy or another outside static analyzer to get the annotations for a property
, but not for code inside the program—but I assume nobody came up with a good answer, or it would have been implemented (or at least discussed in PEP 526 ). IIRC,这在某些方面出现在python-ideas上 - 对于Mypy或其他外部静态分析器而言,获取property
的注释相对容易,但不能用于程序内部的代码 - 但我认为没有人想出一个好的答案,或者它已经实施(或至少在PEP 526中讨论过)。
你定义的函数是Foo.bar.fget
,而不是Foo.bar.__get__
:
typing.get_type_hints(Foo.bar.fget)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.