Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #12144
| References | <CAMX1RokbXLL=typKkOE3HLpxcihJGfnSLkcivyLZypXqgvj1fg@mail.gmail.com> <j32uc8$b8k$1@dough.gmane.org> |
|---|---|
| From | Adam Jorgensen <adam.jorgensen.za@gmail.com> |
| Date | 2011-08-24 16:30 +0200 |
| Subject | Re: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data... |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.392.1314196255.27778.python-list@python.org> (permalink) |
Thanks :-) Sorry about the size, I wasn't sure what was relevant... On 24 August 2011 15:29, Peter Otten <__peter__@web.de> wrote: > 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. > > -- > http://mail.python.org/mailman/listinfo/python-list >
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data... Adam Jorgensen <adam.jorgensen.za@gmail.com> - 2011-08-24 16:30 +0200 Re: Weird interaction with nested functions inside a decorator-producing function and closuring of outer data... Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-08-25 10:54 +1000
csiph-web