How to inject variable into scope with a decorator?

前端 未结 11 2095
我寻月下人不归
我寻月下人不归 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 17:51

    Here is a simple demonstration of using a decorator to add a variable into the scope of a function.

    >>> def add_name(name):
    ...     def inner(func):
    ...         # Same as defining name within wrapped
    ...         # function.
    ...         func.func_globals['name'] = name
    ...
    ...         # Simply returns wrapped function reference.
    ...         return func
    ... 
    ...     return inner
    ...
    >>> @add_name("Bobby")
    ... def say_hello():
    ...     print "Hello %s!" % name
    ...
    >>> print say_hello()
    Hello Bobby!
    >>>
    

提交回复
热议问题