python - 在 Python 3.5.2 中解压 Optional 类型注解

标签 python python-3.x annotations type-hinting

给出这个例子:

import typing

def foo(bar: int = None):
    pass

typing.get_type_hints(foo)

bar 的类型提示是 typing.Union[int, None]。我如何从中获取 int__args____parameters__ 属性在 Python 3.5.2 中似乎都不起作用。


更具体地说,我正在尝试编写一个通用装饰器来检查函数的签名并对参数执行特定操作。为此,它需要从诸如 Optional[T] 的注释中获取类,然后使用 T:

annot = typing.Optional[T]
cls = # MAGIC?!
assert cls is T

最佳答案

3.5.2 中,要获取 Union 的参数,您必须使用 __union_params__

>>> from typing import Union
>>> d = Union[int, str]
>>> print(*d.__union_params__)
<class 'int'> <class 'str'>

不幸的是,这似乎适用于 3.5.2,它在 3.5.3 中被更改为使用 __args__ :

>>> from typing import Union
>>> t = Union[int, str]
>>> t.__union_params__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_Union' object has no attribute '__union_params__'
>>> print(*t.__args__)
<class 'int'> <class 'str'>

并在以后的版本(3.63.7)中保留了 __args__

这是由于打字模块的临时状态。内部 API 的许多方面在微版本之间发生了变化,因此您可能不得不处理许多晦涩的变化。

关于python - 在 Python 3.5.2 中解压 Optional 类型注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198178/

相关文章:

validation - 在 Kotlin 中,根据属性的类型限制注解目标

java - 我应该如何正确使用@Value?

Java:注释中注释的目的?

python - 使用 xlrd 读取包含中文和/或印地语字符的 Excel xls 文件

python - 在 Python 中实现快速排序

python - 如何向一个键添加多个列表?

python-3.x - 使用 Python 连接 HBase 的推荐方法是什么?

python - 可以使用 cmd ">>"登录 Django 开发服务器吗?

python - 使用 virtualenv 的 Celery 的第一步

python-3.x - 如何确保tkinter中不跳过 "bind"命令?