How to inject variable into scope with a decorator

2019-01-31 15:48发布

[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 decorator that does something like injecting a name into the scope of another function (such that the name does not leak outside the decorator's scope). For example, if I have a function that says to print a variable named var that has not been defined, I would like to define it within a decorator where it is called. Here is an example that breaks:

c = 'Message'

def decorator_factory(value):
    def msg_decorator(f):
        def inner_dec(*args, **kwargs):
            var = value
            res = f(*args, **kwargs)
            return res
        return inner_dec
    return msg_decorator

@decorator_factory(c)
def msg_printer():
    print var

msg_printer()

I would like it to print "Message", but it gives:

NameError: global name 'var' is not defined

The traceback even points to wher var is defined:

<ipython-input-25-34b84bee70dc> in inner_dec(*args, **kwargs)
      8         def inner_dec(*args, **kwargs):
      9             var = value
---> 10             res = f(*args, **kwargs)
     11             return res
     12         return inner_dec

So I don't understand why it can't find var.

Is there any way to do something like this?

7条回答
The star\"
2楼-- · 2019-01-31 16:33

Here's a way of injecting multiple variables into a function's scope in a manner somewhat to similar to what @Martijn Pieters does in his answer. I'm posting it primarily because it's a more general solution than applying the decorator multiple times as would be required doing the same thing with the code in Martijn's (and many of the other) answers.

from functools import wraps

def inject_variables(context):
    """ Decorator factory. """
    def variable_injector(func):
        @wraps(func)
        def decorator(*args, **kwargs):
            try:
                func_globals = func.__globals__  # Python 2.6+
            except AttributeError:
                func_globals = func.func_globals  # Earlier versions.

            saved_values = func_globals.copy()  # Shallow copy of dict.
            func_globals.update(context)

            try:
                result = func(*args, **kwargs)
            finally:
                func_globals = saved_values  # Undo changes.

            return result

        return decorator

    return variable_injector

if __name__ == '__main__':
    namespace = {'a': 5, 'b': 3}

    @inject_variables(namespace)
    def test():
        print('a:', a)
        print('b:', b)

    test()
查看更多
登录 后发表回答