【问题标题】:How to reset a global variable and pass it to Decorator如何重置全局变量并将其传递给装饰器
【发布时间】:2021-05-02 23:18:45
【问题描述】:

如何将 A 和 B 的最新值传递给装饰器?

我必须遵循代码,

A = "orginary"
B = "guy"

def caller_func(**kwargs):
 # few lines of logic here 
 global A , B
 A = "Super"
 B = "Mario"
 decorated_fn_1(**kwargs)

@some_decorator(
new_a = A
new_B = B)
def decorated_fn_1(**kwargs):
 # few lines of logic here 
 # decorator functionality called 


"""
Note: Assume some_decorator does something with A and B

"""
  

目的是为装饰器制作A和B的最新变量值。

感谢您的帮助。

【问题讨论】:

    标签: python function decorator python-3.8


    【解决方案1】:

    我会让装饰器代表函数接受额外的参数,而不是使用全局变量。包装器可以提供一些默认值,如果需要,可以选择性地覆盖它们:

    def some_decorator(a, b):
        def inner(func):
            def wrapper(*args, a=a, b=b, **kwargs):
                print(f"{a=}, {b=}")
                return func(*args, **kwargs)
    
            return wrapper
    
        return inner
    
    
    @some_decorator(1, 2)
    def foo(var):
        print(var)
    
    
    foo("test1")
    foo("test2", a=3, b=4)
    

    输出:

    a=1, b=2
    test1
    a=3, b=4
    test2
    

    【讨论】:

    • 感谢您的回复。我喜欢这个想法,但我需要让装饰器可以使用内部函数变量。在我的问题中,我受限于上述代码签名。不过我可以删除 Globals。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2020-07-26
    • 2012-12-13
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多