Python函数参数类型校验时如何获取参数名用于报错提示
解决方案
方案1:最简实现(推荐,零额外复杂度)
Python 3.8及以上版本支持f-string自记录表达式语法,直接在变量后加=即可在输出中自动携带参数名,完全满足你的需求,不需要额外引入依赖或写复杂逻辑:
def do_stuff(x): if not isinstance(x, int): # 类型错误优先使用TypeError而非ValueError,符合Python异常分类规范 raise TypeError(f"{x=} is not int type") # 你的业务逻辑
传入非int参数时的报错示例:
TypeError: x='test_str' is not int type
你实际使用pandas的场景对应写法如下:
import pandas as pd def do_stuff(x): if not isinstance(x, pd.Series): raise TypeError(f"{x=} is not pandas.Series type") # 你的业务逻辑
即使误传入DataFrame,报错开头也会直接显示x=,不需要看完整个DataFrame输出就能定位问题参数。
方案2:通用校验装饰器(适合多函数批量校验场景)
如果你有大量函数都需要做参数类型校验,可以封装通用装饰器,一次编写全局复用,自动携带函数名、参数名、预期类型信息:
import inspect from functools import wraps from typing import Callable, Any def param_type_check(**type_map): def decorator(func: Callable) -> Callable: func_sig = inspect.signature(func) @wraps(func) def wrapper(*args, **kwargs) -> Any: bound_params = func_sig.bind(*args, **kwargs) bound_params.apply_defaults() for param_name, expect_type in type_map.items(): param_val = bound_params.arguments[param_name] if not isinstance(param_val, expect_type): raise TypeError(f"Argument {param_name} to {func.__name__}({param_name}) is not {expect_type.__name__}") return func(*args, **kwargs) return wrapper return decorator
使用方式:
import pandas as pd @param_type_check(x=pd.Series, count=int) def do_stuff(x, count): # 无需手动写校验逻辑 pass
传参错误时报错示例:
TypeError: Argument x to do_stuff(x) is not Series
内容的提问来源于stack exchange,提问作者phollox
相关产品推荐
相关产品推荐

