在Python 3.10及以上版本中,UnionType
被引入作为 typing.Union
的类型提示的一部分。为了可靠地检查 UnionType
中的子成员类型,你可以使用 isinstance()
函数结合 typing
模块中的 get_args()
和 get_origin()
函数。
以下是一个示例,展示如何检查 UnionType
中的子成员类型:
from typing import Union, get_args, get_origin
def check_union_member(value, union_type):
# 获取 Union 类型的原始类型和参数
origin = get_origin(union_type)
args = get_args(union_type)
# 检查是否是 Union 类型
if origin is Union:
# 遍历 Union 的所有子类型
for arg in args:
if isinstance(value, arg):
return True
return False
else:
# 如果不是 Union 类型,直接检查类型
return isinstance(value, union_type)
# 示例使用
value = 42
union_type = Union[int, str]
if check_union_member(value, union_type):
print(f"{value} 是 {union_type} 的一个子类型")
else:
print(f"{value} 不是 {union_type} 的子类型")
get_origin(union_type)
: 获取 union_type
的原始类型。对于 Union[int, str]
,get_origin
会返回 typing.Union
。get_args(union_type)
: 获取 union_type
的类型参数。对于 Union[int, str]
,get_args
会返回 (int, str)
。isinstance(value, arg)
: 检查 value
是否是 arg
类型的实例。Union[int, str]
可以直接写成 int | str
,但 get_origin
和 get_args
仍然适用。Union
或泛型类型),你可能需要递归地处理 get_args
的结果。通过这种方式,你可以可靠地检查 UnionType
中的子成员类型。