Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #12142
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data... |
| Date | 2011-08-24 15:29 +0200 |
| Organization | None |
| References | <CAMX1RokbXLL=typKkOE3HLpxcihJGfnSLkcivyLZypXqgvj1fg@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.390.1314192603.27778.python-list@python.org> (permalink) |
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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
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
csiph-web