How to inject variable into scope with a decorator?

前端 未结 11 2089
我寻月下人不归
我寻月下人不归 2020-12-04 17:31

[Disclaimer: there may be more pythonic ways of doing what I want to do, but I want to know how python\'s scoping works here]

I\'m trying to find a way to make a dec

11条回答
  •  粉色の甜心
    2020-12-04 18:18

    You can't. Scoped names (closures) are determined at compile time, you cannot add more at runtime.

    The best you can hope to achieve is to add global names, using the function's own global namespace:

    def decorator_factory(value):
        def msg_decorator(f):
            def inner_dec(*args, **kwargs):
                g = f.__globals__  # use f.func_globals for py < 2.6
                sentinel = object()
    
                oldvalue = g.get('var', sentinel)
                g['var'] = value
    
                try:
                    res = f(*args, **kwargs)
                finally:
                    if oldvalue is sentinel:
                        del g['var']
                    else:
                        g['var'] = oldvalue
    
                return res
            return inner_dec
        return msg_decorator
    

    f.__globals__ is the global namespace for the wrapped function, so this works even if the decorator lives in a different module. If var was defined as a global already, it is replaced with the new value, and after calling the function, the globals are restored.

    This works because any name in a function that is not assigned to, and is not found in a surrounding scope, is marked as a global instead.

    Demo:

    >>> c = 'Message'
    >>> @decorator_factory(c)
    ... def msg_printer():
    ...     print var
    ... 
    >>> msg_printer()
    Message
    >>> 'var' in globals()
    False
    

    But instead of decorating, I could just as well have defined var in the global scope directly.

    Note that altering the globals is not thread safe, and any transient calls to other functions in the same module will also still see this same global.

提交回复
热议问题