插件窝 干货文章 Python UnionType类型如何判断是否包含特定类型?

Python UnionType类型如何判断是否包含特定类型?

类型 Union 联合 type 887    来源:    2025-03-15

在Python 3.10及以上版本中,引入了UnionType,它允许你在类型注解中使用|操作符来表示联合类型。例如,int | str表示一个类型可以是intstr

要判断一个UnionType是否包含特定类型,可以使用isinstance()函数结合typing模块中的get_args()函数。get_args()函数可以获取联合类型中的所有类型参数。

以下是一个示例代码,展示如何判断一个UnionType是否包含特定类型:

from typing import Union, get_args

# 定义一个联合类型
MyUnionType = Union[int, str, float]

# 获取联合类型中的所有类型参数
types_in_union = get_args(MyUnionType)

# 要检查的类型
target_type = str

# 判断目标类型是否在联合类型中
if target_type in types_in_union:
    print(f"{target_type} is in the union type.")
else:
    print(f"{target_type} is not in the union type.")

解释:

  1. Union[int, str, float]:定义了一个联合类型,表示可以是intstrfloat
  2. get_args(MyUnionType):获取联合类型中的所有类型参数,返回一个包含所有类型的元组。
  3. target_type in types_in_union:检查目标类型是否在联合类型的类型参数中。

输出:

如果target_typestr,输出将是:

str is in the union type.

如果target_typelist,输出将是:

list is not in the union type.

注意事项:

  • get_args()函数在Python 3.8及以上版本中可用。
  • 如果你使用的是Python 3.10及以上版本,可以直接使用|操作符来定义联合类型,而不需要使用Union

希望这个解释对你有帮助!