Weird interaction with nested functions inside a decorator-producing function and closuring of outer data...

Peter Otten __peter__ at
Wed Aug 24 09:29:58 EDT 2011

Adam Jorgensen wrote:

> Hi all, I'm experiencing a weird issue with closuring of parameters
> and some nested functions I have inside two functions that
> return decorators. I think it's best illustrated with the actual code:

You should have made an effort to reduce its size
> # This decorator doesn't work. For some reason python refuses to
> closure the *decode_args parameter into the scope of the nested
> decorate and decorate_with_rest_wrapper functions
> # Renaming *decode_args has no effect
> def rest_wrapper(*decode_args, **deco_kwargs):
>     def decorate(func):
>         argspec = getfullargspec(func)
>         decode_args = [argspec.args.index(decode_arg) for decode_arg
> in decode_args]

I didn't read the whole thing, but:

>>> def f(a):
...     def g():
...             a = a + 42
...             return a
...     return g
>>> f(1)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in g
UnboundLocalError: local variable 'a' referenced before assignment

Python treats variables as local if you assign a value to them anywhere in 
the function. The fix is easy, just use another name:

>>> def f(a):
...     def g():
...             b = a + 42
...             return b
...     return g
>>> f(1)()

In Python 3 you can also use the nonlocal statement.

More information about the Python-list mailing list