在Python 3.10及以上版本中,引入了UnionType
,允许你在类型提示中使用|
操作符来表示联合类型。例如,int | str
表示一个类型可以是int
或str
。
要判断一个对象是否是联合类型中的某个成员类型,可以使用isinstance()
函数。isinstance()
函数可以接受一个元组作为第二个参数,用于检查对象是否是元组中任意一个类型的实例。
以下是一个示例,展示了如何在UnionType
类型提示中判断成员类型:
def check_type(value: int | str):
if isinstance(value, int):
print(f"{value} is an integer.")
elif isinstance(value, str):
print(f"{value} is a string.")
else:
print(f"{value} is neither an integer nor a string.")
# 测试
check_type(42) # 输出: 42 is an integer.
check_type("hello") # 输出: hello is a string.
check_type(3.14) # 输出: 3.14 is neither an integer nor a string.
在这个例子中,check_type
函数接受一个类型为int | str
的参数value
。通过isinstance()
函数,我们可以判断value
是int
类型还是str
类型,并相应地输出结果。
如果你需要处理更复杂的联合类型,或者需要动态地检查类型,可以使用typing
模块中的get_args
和get_origin
函数来获取联合类型的成员类型。例如:
from typing import get_args, get_origin
def check_union_type(value, union_type):
if get_origin(union_type) is Union:
types = get_args(union_type)
if any(isinstance(value, t) for t in types):
print(f"{value} is one of the types in {union_type}.")
else:
print(f"{value} is not one of the types in {union_type}.")
else:
print(f"{union_type} is not a Union type.")
# 测试
from typing import Union
check_union_type(42, Union[int, str]) # 输出: 42 is one of the types in Union[int, str].
check_union_type("hello", Union[int, str]) # 输出: hello is one of the types in Union[int, str].
check_union_type(3.14, Union[int, str]) # 输出: 3.14 is not one of the types in Union[int, str].
在这个例子中,check_union_type
函数可以动态地检查一个值是否是某个联合类型的成员类型。get_origin
函数用于获取联合类型的原始类型(即Union
),get_args
函数用于获取联合类型的成员类型。