Skip to main content
 首页 » 编程设计

python:用默认的kwargs装饰函数

2025年05月04日9shangdawei

我怎样才能定义一个装饰器 decor 来完成这项工作?有很多关于此的帖子,但我仍然没有找到解决方案。也许这是一个非常糟糕的主意。

示例 1,编写一个在应用装饰器之前中断的函数:

defaults = {'a': 1, 'b': 2} 
 
@decor(defaults) 
def f(x): 
    print(x, a, b) 

示例 2:

defaults = {'a': 1, 'b': 2} 
 
@decor(defaults) 
def fun(x): 
   print(locals()) 
 
f(3) 

应该给

{'b': 2, 'x': 3, 'a': 1} 

或者可能更清楚,我希望装饰器修改签名,以便 help(f) 给出

Help on function f in module __main__: 
 
f(x, a=1, b=2) 

请您参考如下方法:

好吧,你已经被警告过这是不安全的,但是为了好玩,这个装饰器必须工作,不管装饰函数是否接收 kwargs 或不

import inspect as insp 
 
def modify(f, defaults): 
    lines = insp.getsourcelines(f)[0] 
    lines.pop(0) # remove decorator heading 
    for k, v in defaults.items(): 
        lines.insert(1, '    %s = %s\n' % (k, v)) 
    exec ''.join(lines) 
    return locals()[f.__name__] 
 
def decor(defaults): 
    def wrap(f): 
        def wrapped_f(*args): 
            new_f = modify(f, defaults) 
            return new_f(*args) 
        return wrapped_f 
    return wrap