如何编程生成比给定Python函数多一个参数且签名一致的函数?
问题:编程生成签名一致的扩展Python函数
现有Python函数:
def my_func(first, second=2): return first * second
需要编程生成一个新函数,比原函数多一个带默认值的参数exclamation,目标函数行为如下:
def my_new_func(first, second=2, exclamation='hello'): print(exclamation) return my_func(first, second)
要求新函数的签名必须与上述手动定义的完全一致,使用*args、**kwargs的方式无法满足签名要求,询问最优实现方法。
最优实现方法
标准库方案(无第三方依赖)
借助Python标准库的inspect模块解析原函数的签名,再通过动态代码生成的方式创建签名完全匹配的新函数,步骤如下:
- 提取原函数的参数信息,包括参数名和默认值
- 构造包含新参数的函数定义字符串
- 执行动态代码并绑定新函数对象
示例代码:
import inspect def my_func(first, second=2): return first * second # 获取原函数的签名参数 orig_sig = inspect.signature(my_func) orig_params = list(orig_sig.parameters.values()) # 添加新参数exclamation,带默认值'hello' new_param = inspect.Parameter( 'exclamation', inspect.Parameter.POSITIONAL_OR_KEYWORD, default='hello' ) orig_params.append(new_param) # 构造新函数的参数字符串 param_defs = [] for p in orig_params: if p.default is not inspect.Parameter.empty: param_defs.append(f"{p.name}={repr(p.default)}") else: param_defs.append(p.name) param_str = ', '.join(param_defs) # 动态生成函数代码并执行 func_code = f''' def my_new_func({param_str}): print(exclamation) return my_func(first, second) ''' namespace = {'my_func': my_func} exec(func_code, namespace) my_new_func = namespace['my_new_func']
验证签名是否符合要求:
print(inspect.signature(my_new_func)) # 输出: (first, second=2, exclamation='hello')
第三方库方案(更简洁)
如果可以安装第三方库,makefun是专门处理函数签名动态修改的工具,实现起来更简洁:
import inspect from makefun import wraps def my_func(first, second=2): return first * second # 构造新签名 orig_sig = inspect.signature(my_func) new_params = list(orig_sig.parameters.values()) + [ inspect.Parameter('exclamation', inspect.Parameter.POSITIONAL_OR_KEYWORD, default='hello') ] new_sig = orig_sig.replace(parameters=new_params) # 用makefun包装生成新函数 @wraps(my_func, new_sig=new_sig) def my_new_func(first, second, exclamation='hello'): print(exclamation) return my_func(first, second)
两种方案都能生成签名完全符合要求的新函数,标准库方案无需额外依赖,第三方库方案代码更简洁易维护。
内容的提问来源于stack exchange,提问作者8one6
相关产品推荐
相关产品推荐

