如何更改装饰器内的全局参数并自动重置它?

布拉姆维尔斯特

我正在尝试更改装饰器内的配置字典(因此我不必弄乱函数do_something()本身的代码)。但是,我在将字典“重置”到旧状态时遇到了问题。

我该怎么做呢?还有比这种方法更好的方法do_something()(不更改代码本身)?

我已经尝试了几种关于 CONFIG 变量放置的方法,但最终,全局上下文永远不会重置为原始状态。

import copy

CONFIG = {
    'key': 'value'
}


def alter_dictionary_decorator(function):
    def wrapper():
        old = copy.deepcopy(CONFIG)
        CONFIG['key'] = 'other_value'
        func = function()
        config = old # <- can't put 'CONFIG = old' here
        return func
    return wrapper

@alter_dictionary_decorator
def do_something():
    print(CONFIG['key'])


if __name__ == '__main__':
    print(CONFIG['key'])
    do_something()
    print(CONFIG['key'])

预期结果 = 'value', 'other_value', 'value'

观察结果 = 'value', 'other_value', 'other_value'

游戏玩家007

您需要使用global关键字来修改具有全局作用域的变量。另外,config = old应该是CONFIG = old

以下代码按您的要求工作:

import copy

CONFIG = {
    'key': 'value'
}


def alter_dictionary_decorator(function):
    def wrapper():
        global CONFIG
        old = copy.deepcopy(CONFIG)
        CONFIG['key'] = 'other_value'
        func = function()
        CONFIG = old
        return func
    return wrapper

@alter_dictionary_decorator
def do_something():
    print(CONFIG['key'])


if __name__ == '__main__':
    print(CONFIG['key'])
    do_something()
    print(CONFIG['key'])

输出为:

value
other_value
value

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章