Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12142 > unrolled thread

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

Started byPeter Otten <__peter__@web.de>
First post2011-08-24 15:29 +0200
Last post2011-08-24 15:29 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data... Peter Otten <__peter__@web.de> - 2011-08-24 15:29 +0200

#12142 — Re: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data...

FromPeter Otten <__peter__@web.de>
Date2011-08-24 15:29 +0200
SubjectRe: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data...
Message-ID<mailman.390.1314192603.27778.python-list@python.org>
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)()
43

In Python 3 you can also use the nonlocal statement.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web