在 Python 3.5.2 中解压可选类型注释

dec*_*eze 8 python annotations type-hinting python-3.x

给出这个例子:

import typing

def foo(bar: int = None):
    pass

typing.get_type_hints(foo)
Run Code Online (Sandbox Code Playgroud)

的类型提示bartyping.Union[int, None]. 我该如何int从中得到呢?__args__Nor属性__parameters__似乎在 Python 3.5.2 中不起作用。


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

annot = typing.Optional[T]
cls = # MAGIC?!
assert cls is T
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 8

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

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

不幸的是,这似乎适用于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'>
Run Code Online (Sandbox Code Playgroud)

并一直保留__args__在以后的版本中(3.63.7)。

这是由于打字模块的临时状态造成的。内部 API 的许多方面都在微型版本之间发生变化,因此您可能必须处理许多晦涩的更改。