如何在Python函数中验证参数类型(含typing模块类型)
实现支持复杂类型的Python参数类型验证函数
下面是一个支持基础类型、泛型容器(如List、Iterable)及多类型元素的类型验证函数,完全满足你的需求:
import typing from typing import Any, Type def check_types(value: Any, expected_type: Type[Any], argname: str, funcname: str) -> None: # 处理int、str这类基础原生类型 if isinstance(expected_type, type): if not isinstance(value, expected_type): raise TypeError(f"'{argname}' to '{funcname}' must be type '{expected_type.__name__}', not '{type(value).__name__}'") return # 解析泛型类型的原始类型与参数(如List[Union[int, str]]的原始类型是list,参数是(int, str)) origin_type = typing.get_origin(expected_type) type_args = typing.get_args(expected_type) # 非泛型的特殊类型直接校验 if origin_type is None: if not isinstance(value, expected_type): raise TypeError(f"'{argname}' to '{funcname}' must be type '{expected_type}', not '{type(value).__name__}'") return # 校验值是否属于泛型对应的原始容器类型 if not isinstance(value, origin_type): raise TypeError(f"'{argname}' to '{funcname}' must be type '{expected_type}', not '{type(value).__name__}'") # 无类型参数的泛型(如List)无需校验元素 if not type_args: return # 遍历容器元素,校验每个元素是否符合任意指定类型 for elem in value: elem_valid = False for arg_type in type_args: try: check_types(elem, arg_type, f"{argname}[element]", funcname) elem_valid = True break except TypeError: continue if not elem_valid: raise TypeError(f"Element '{elem}' in '{argname}' to '{funcname}' must be one of types {type_args}, not '{type(elem).__name__}'")
用法示例
注意:标准Python typing中,List仅接受单个类型参数,若要表示元素可以是int或str,需用List[Union[int, str]](你示例中的List[int, str]是不合法语法),以下是正确使用方式:
from typing import List, Union def some_function(arg1: int, arg2: List[Union[int, str]]): check_types(arg1, int, argname="arg1", funcname="some_function") check_types(arg2, List[Union[int, str]], argname="arg2", funcname="some_function") # 正常调用(无报错) some_function(1, [2, "test"]) # 测试错误场景1:arg2传入int而非列表 try: some_function(1, 3) except TypeError as e: print(e) # 输出:'arg2' to 'some_function' must be type 'typing.List[typing.Union[int, str]]', not 'int' # 测试错误场景2:列表包含不符合类型的元素 try: some_function(1, [2, 3.14]) except TypeError as e: print(e) # 输出:Element '3.14' in 'arg2' to 'some_function' must be one of types (<class 'int'>, <class 'str'>), not 'float'
核心特性
- 支持基础类型(int、str、bool等)的校验
- 支持泛型容器(List、Iterable、Tuple等)的校验
- 支持多类型元素(如
List[Union[int, str]]表示列表元素可以是int或str) - 支持嵌套泛型(如
List[List[int]])的递归校验 - 生成清晰的错误提示,包含参数名、函数名及类型不匹配信息
内容的提问来源于stack exchange,提问作者user20392744
相关产品推荐
相关产品推荐

