Python类型提示中UnionType类型如何判断是否包含特定类型?(类型.如何判断.特定.包含.提示...)
本文探讨Python类型提示中UnionType的成员访问,特别是如何判断UnionType是否包含特定类型,例如str。 在函数参数类型提示中,直接检查UnionType是否包含特定类型并非易事。
问题:当函数参数类型为UnionType时,例如def func(name: str | None): pass,无法直接使用in操作符或迭代访问其成员来判断是否包含str。
解决方案:typing.get_args函数是关键。它可以提取泛型类型的参数。我们可以利用它来解决这个问题。
方法一:使用typing.get_args
以下代码演示如何使用typing.get_args来判断UnionType是否包含str:
from typing import Union, Callable from types import UnionType from inspect import signature import typing def check_func_args_hints(func: Callable) -> bool: for param in signature(func).parameters.values(): annotation = param.annotation if isinstance(annotation, UnionType): if str in typing.get_args(annotation): return True else: return False elif annotation is str: return True else: return False def get_score(name: str | None = None) -> float | None: pass def another_func(name: int): pass def yet_another_func(name: float | None): pass print(check_func_args_hints(get_score)) # True print(check_func_args_hints(another_func)) # False print(check_func_args_hints(yet_another_func)) # False
check_func_args_hints函数获取函数参数的类型提示。如果是UnionType,则使用typing.get_args提取所有类型,并检查str是否存在。如果不是UnionType,则直接检查是否为str。
方法二:使用isinstance (局限性更大)
另一种方法是利用isinstance,但它仅适用于可通过空字符串实例化判断的类型:
# ... (其他代码同上) ... elif isinstance("", param.annotation): return True else: return False
这种方法的局限性在于,并非所有类型都能够用空字符串进行有效的实例化检查。
总结:typing.get_args方法更可靠,因为它直接处理UnionType的组成类型,而不会依赖于类型实例化的特性。 因此,推荐使用第一种方法来判断UnionType中是否包含特定类型。
以上就是Python类型提示中UnionType类型如何判断是否包含特定类型?的详细内容,更多请关注知识资源分享宝库其它相关文章!