怎么在Python中进行动态类型检查与参数校验
使用 type() 获取变量实际类型,用 isinstance() 进行继承兼容的类型判断。对于函数参数校验,推荐结合 inspect 模块与自定义装饰器实现动态检查。

type() 与 isinstance() 的区别
type() 返回对象的精确类对象,常用于严格匹配;isinstance() 检查对象是否属于指定类或其子类,适用于多态场景。

当需要判断一个对象是否为特定类型时,两者表现不同。例如,若子类继承了父类,isinstance() 会返回 True,而 type() 仅当完全一致时才返回 True。在动态类型检查中,优先使用 isinstance() 以保证代码的扩展性。
基于 inspect 的参数校验装饰器
通过定义一个装饰器,利用 inspect.signature 获取函数签名,并在调用前对传入参数进行类型比对。

import inspect
from typing import get_type_hints, Union
def type_check(func):
hints = get_type_hints(func)
sig = inspect.signature(func)
def wrapper(*args, **kwargs):
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
for name, value in bound_args.arguments.items():
if name not in hints:
continue
expected = hints[name]
# 处理 Optional 类型 (Union[..., None])
is_optional = False
check_types = []
if hasattr(expected, '__origin__') and expected.__origin__ is Union:
args_of_union = expected.__args__
if type(None) in args_of_union:
is_optional = True
check_types = [t for t in args_of_union if t is not type(None)]
else:
check_types = list(args_of_union)
else:
check_types = [expected]
if is_optional and value is None:
continue
if not any(isinstance(value, t) for t in check_types):
raise TypeError(
f"Argument '{name}' expected {check_types}, got {type(value)}"
)
return func(*args, **kwargs)
return wrapper
@type_check
def greet(name: str, age: int):
print(f"Hello {name}, you are {age}")
# 测试用例
greet("Alice", 25) # 正常执行
greet(123, 25) # 触发 TypeError
运行程序后,第一行调用将正常打印 "Hello Alice, you are 25"。第二行调用因第一个参数应为字符串却传入整数,会抛出 TypeError 并提示具体参数名和期望类型。这验证了装饰器在运行时成功拦截并校验了输入。
该方案允许在运行时动态拦截函数调用,提取参数名和预期类型,从而实现对任意函数的通用校验逻辑。
处理默认参数与可选类型的校验细节
当参数存在默认值或类型为 Optional 时,需特殊处理 None 值以避免误报。
在实现校验逻辑时,应检查参数是否有默认值,若有则跳过校验或允许 None。同时,对于 Union 类型(如 int | str),需遍历所有可能类型进行匹配。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









