Recursive inner function... How?

Bjorn Pettersen pbjorn at uswest.net
Mon Jan 1 13:30:48 EST 2001


Thanks Fredrik!

Fredrik Lundh wrote:

> Bjorn Pettersen wrote:
> > however, in 2.0 that gives an "UnboundLocalError: Local variable 'inner'
> > referenced before assignment".
>
> in this case, the assignment is done by "def":
>
> >     def outer():
> >         def inner(inner=inner <- reference):
> >             inner()
> >         <- assignment statement ends here
> >         inner()
> >
> >     outer()
> >
>
> > Please tell me I'm doing something wrong?
>
> you're trying to use recursive inner functions ;-)

I figured that was the root cause <wink>

> the easiest fix is to do as Guido intended, and move
> "inner" to the global scope.  you can either move the
> entire function to the right place, or cheat:
>
>     def outer():
>         global inner
>         def inner():
>             inner()
>         inner()
>
>     outer()

This is so cute I just had to use it -- I'm the only one using this code, so
at least I'm only shooting myself in the foot (outer is really a method in a
longish class, so I would prefer to keep inner textually close). It isn't
immediately clear to me what is going on though... My guess is that the global
statement creates an entry in the global dict, and the def inner assigns a new
value to it... (am I close?)

-- bjorn





More information about the Python-list mailing list