Python场景下:如何在runner.py适配参数不同的important前缀函数
解决方案
可以利用Python的inspect模块获取函数的参数签名,动态匹配传递的参数,完全在runner.py中处理问题,无需修改utils.py的函数定义。
修正后的runner.py代码
import utils import inspect if __name__ == "__main__": first_value = 'first value' second_value = 'second value' third_value = 'third value' # 遍历utils模块中的所有成员 for func_name, func in utils.__dict__.items(): # 筛选出以'important'开头的可调用函数 if func_name.startswith('important') and callable(func): # 获取函数的参数签名 sig = inspect.signature(func) param_count = len(sig.parameters) # 根据参数数量匹配对应的值 if param_count == 1: func(first_value) elif param_count == 2: func(first_value, second_value) elif param_count == 3: func(first_value, second_value, third_value)
关键说明
inspect.signature(func):获取函数的签名对象,从中提取参数的数量和属性信息。len(sig.parameters):统计函数需要的位置参数总数(基于已知所有目标函数都包含first_arg的前提)。- 匹配逻辑:按参数数量1/2/3分别传递对应的值,从根源避免参数不匹配的报错。
可选优化(适配带默认值的参数)
如果后续函数可能新增带默认值的参数,可以进一步优化逻辑,只传递无默认值的必填参数:
import utils import inspect if __name__ == "__main__": first_value = 'first value' second_value = 'second value' third_value = 'third value' args = [first_value, second_value, third_value] for func_name, func in utils.__dict__.items(): if func_name.startswith('important') and callable(func): sig = inspect.signature(func) # 筛选出无默认值的必填参数 required_params = [p for p in sig.parameters.values() if p.default is inspect.Parameter.empty] # 截取对应数量的参数传递 func(*args[:len(required_params)])
这个版本更灵活,即使函数后续新增带默认值的参数,也不会影响现有调用逻辑。
内容的提问来源于stack exchange,提问作者amit
相关产品推荐
相关产品推荐

