如何重置全局变量并将其传递给Decorator



如何将A和B的最新值传递给Decorator ?

我必须遵循代码,

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的最新变量值赋给装饰器。

谢谢你的帮助。

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

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

相关内容

  • 没有找到相关文章

最新更新