gpt4 book ai didi

python - 如何从装饰器访问装饰函数中的局部变量

转载 作者:行者123 更新时间:2023-11-28 16:27:04 27 4
gpt4 key购买 nike

我刚开始使用 Python 中的装饰器。我目前无法找到处理此用例的最佳方法。由于装饰函数无法从装饰器访问局部变量。

schema = {
'lang': {'type': 'string', 'required':True}
}

def validate(schema):
def my_decorator(func):
def wrapper(*args, **kwargs):
# Read from request body args[1]
# Validate the json is in fact correct
valid_json = json.loads(body.decode('utf-8'))
# Compare valid_json to the schema using "Cerberus"
return args, kwargs
return wrapper
return my_decorator

@validate(schema)
def main_function(self, req, resp):
# call database with valid_json

我的问题是:如何从我的修饰函数访问 valid_json 以便之后能够插入到我的数据库中。这种情况的最佳做法是什么?

编辑:我正在运行 pypy 2.4

最佳答案

您不能直接这样做。被装饰函数的作用域是在被装饰器包装之前设置的,它与装饰器添加包装器建立的作用域没有任何联系。

你能做的最好的事情就是让函数接受装饰器传递的附加参数,例如:

@validate(schema)
def main_function(self, req, resp, valid_json=None):
# call database with valid_json

装饰器在调用包装函数时显式添加 valid_json=valid_json,例如返回 func(*args, **kwargs, valid_json=valid_json)

关于python - 如何从装饰器访问装饰函数中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35754307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com