在Python的类型提示中,Union
类型用于表示一个值可以是多种类型中的一种。从Python 3.10开始,Union
类型被 |
操作符所取代,例如 int | str
表示一个值可以是 int
或 str
类型。
如果你想判断一个 Union
类型(或 |
操作符生成的类型)是否包含特定类型,可以使用 typing
模块中的 get_args
函数来获取 Union
类型的参数,然后检查特定类型是否在这些参数中。
以下是一个示例:
from typing import Union, get_args
# 定义一个 Union 类型
MyUnionType = Union[int, str, float]
# 获取 Union 类型的参数
args = get_args(MyUnionType)
# 检查特定类型是否在 Union 类型中
if int in args:
print("MyUnionType 包含 int 类型")
else:
print("MyUnionType 不包含 int 类型")
在Python 3.10及以上版本中,你可以使用 |
操作符来定义联合类型,并且仍然可以使用 get_args
来获取类型参数:
from typing import get_args
# 使用 | 操作符定义联合类型
MyUnionType = int | str | float
# 获取联合类型的参数
args = get_args(MyUnionType)
# 检查特定类型是否在联合类型中
if int in args:
print("MyUnionType 包含 int 类型")
else:
print("MyUnionType 不包含 int 类型")
get_args
函数可以获取 Union
类型或 |
操作符生成的联合类型的参数。这种方法适用于Python 3.7及以上版本。