You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python装饰器中获取被装饰函数的关键字参数默认值

问题原因

Python 函数的参数默认值是存储在函数对象自身的属性中,仅调用时主动传入的参数才会被解析到装饰器 wrapper 接收到的 *args 与 **kwargs 中。你调用 say_hi() 时没有传入任何参数,因此 wrapper 拿到的 args、kwargs 自然为空,参数默认值是被装饰函数执行时才会主动读取的配置,不会自动带入装饰器的入参里。

解决方法

可以借助 Python 标准库 inspect 的签名绑定能力,自动补全参数默认值,示例实现如下:

import inspect

def print_all_args(func):
    # 提前获取被装饰函数的参数签名
    func_sig = inspect.signature(func)
    def wrapper(*args, **kwargs):
        # 绑定实际入参到签名
        bound_params = func_sig.bind(*args, **kwargs)
        # 自动填充未传参的默认值
        bound_params.apply_defaults()
        # bound_params.arguments 中包含所有参数(含使用默认值的参数)
        print(bound_params.arguments)
        return func(*args, **kwargs)
    return wrapper

@print_all_args
def say_hi(text='hi'):
    return text

运行测试

  • 无参调用
say_hi()
# 输出:{'text': 'hi'}
  • 主动传参调用
say_hi(text="hello")
# 输出:{'text': 'hello'}

该方案可以兼容绝大多数参数定义场景,包括可变位置参数、可变关键字参数、仅限关键字参数等

内容的提问来源于stack exchange,提问作者irahorecka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:45:07