Using a decorator to bring variables into decorated function namespace
<p>Say I have a function that looks like this:</p>

<pre><code>def func(arg1, arg2):
    return arg1 + arg2 + arg3
</code></pre>

<p>And I want to bring in <code>arg3</code> using an argument passed to a decorator. Is this possible and if so how would this be done?</p>

<p>I've tried this which was suggested <a href="http://www.saltycrane.com/blog/2010/03/simple-python-decorator-examples/" rel="nofollow">here</a> to be able to pass arguments to decorators:</p>

<pre><code>from functools import wraps

def addarg(arg):
    def decorate(func):
        arg3 = arg
        @wraps(func)
        def wrapped(*args):
            return func(*args)
        return wrapped
    return decorate

@addarg(3)
def func(arg1, arg2):
    return arg1 + arg2 + arg3

if __name__ == "__main__":
    print(func(1, 2))
</code></pre>

<p>But I get this error (understandably):</p>

<pre><code>Traceback (most recent call last):
  File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 19, in &lt;module&gt;
    print(func(1, 2))
  File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 9, in wrapped
    return func(*args)
  File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 16, in func
    return arg1 + arg2 + arg3
NameError: name 'arg3' is not defined
</code></pre>

<p>For my application it would be much nicer to be able to define the function in this way. There are other ways but then more code will have to be added to the body of each function.</p>

<p>It's a little on the hacky side, but this implmentation of the decorator seems to do what you want. The <code>arg3</code> variable had to be made to appear as a global because it's referenced as one in the byte-code generated from the definition of <code>func()</code>, so it's not really considered a function argumentâbut that doesn't appear to matter in this case.</p>

<pre><code>from functools import wraps

def addarg(arg):
    def decorate(func):
        @wraps(func)
        def wrapped(*args):
            global_vars, local_vars = {'func': func, 'args': args}, {}
            func.__globals__.update(arg3=arg)
            exec('_result = func(*args)', global_vars, local_vars)
            return local_vars['_result']
        return wrapped
    return decorate

@addarg(3)
def func(arg1, arg2):
    return arg1 + arg2 + arg3

if __name__ == "__main__":
    print(func(1, 2))  # -&gt; 6
</code></pre>

python function namespaces python-decorators