繁体   English   中英

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

[英]How to change a global parameter inside a decorator and automatically reset it?

我正在尝试更改装饰器内的配置字典(所以我不必弄乱函数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'])

预期结果='价值','other_value','价值'

Observerd results ='value','other_value','other_value'

您需要使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM