strange behaivor of nested function

Chris Angelico rosuav at gmail.com
Sat Jun 7 07:32:25 EDT 2014


On Sat, Jun 7, 2014 at 9:17 PM, 1989lzhh <1989lzhh at gmail.com> wrote:
> def make():
>     def jit(sig):
>         def wrap(function):
>             sig=sig[0] # unbound local error, if change to sig='' would be just fine
>             return function
>         return wrap
>     return jit
> jit=make()
> @jit('')
> def f():
>     pass
>
> It is strange that the interpreter complain about unbound local error.
> please give me some suggestion, thanks!
> Ps: I am using python 2.7

It's quite simple. You're assigning to the name 'sig' inside the
function 'wrap', which means that - in the absence of a declaration -
'sig' is a local name. But before you assign anything to it, you first
try to reference it, by subscripting it (sig[0]). Python doesn't have
a rule about pulling something in from another scope at the same time
as making it local (some languages do, and it's rather handy, but it
can only work with variable declarations), so what you're attempting
to do there simply won't work.

But it seems a little odd anyway. Why do you take the first element of
sig every time the inner function is called? Surely you want to do
that just once?

ChrisA



More information about the Python-list mailing list