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

标签 python python-3.x

如何访问使用 @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/

相关文章:

python - 权限不足 : plone. app.multilingual [1.x] - 翻译原型(prototype)内容

python - 在特定时间步重置数据帧列中的值并减去行

python - 当在查询中使用fields选项时,elasticsearch-py搜索返回列表对象

python - 计算具有非唯一日期索引的数据帧的滚动中位数

python - 如何在 Mako 模板中使用 Py3k 风格的字符串格式?

python - 试图在数据集中找到最优价格点

python - 连接中止 .', BadStatusLine("''",) 在服务器上?

html - Python3 html转pdf

python - 将项目插入字典的中间

python - 在Python中计算较大数字的模数