使用typing.Union时,我无法获得有关该参数的任何信息
import typing
x = typing.Union[str,int]
print(typing.get_args(x))输出:(<class 'str'>, <class 'int'>)
def f(y: typing.Union[str,int]):
print(typing.get_args(y))
f(1)输出:()
发布于 2022-12-01 21:38:18
x 是类型的结合。y属于联合类型(即int类型或str类型)。
试试print(type(x))和print(type(y))。
在您的函数签名中,您只是注释了y应该是str类型还是int类型。因此,当您将get_args传递给函数时,您将在int上调用1。
代码中的x只是该类型union对象的别名。
事实上,你可以这样做:
from typing import Union
x = Union[str, int]
def f(y: x):
...这相当于:
from typing import Union
def f(y: Union[str, int]):
...发布于 2022-12-02 08:44:07
您可以使用typing.get_type_hints()获取f的类型注释。
def f(y: typing.Union[str,int]):
print(typing.get_type_hints(f))
f(1)https://stackoverflow.com/questions/74647685
复制相似问题