Recursive inner function... How?

Fredrik Lundh fredrik at effbot.org
Mon Jan 1 07:08:14 EST 2001


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 ;-)

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()

(iirc, there's a FAQ entry with more info on this, but the
entire FAQ seems to have disappeared.  a ++Y2K bug?)

btw, also see:
http://python.sourceforge.net/peps/pep-0227.html

</F>





More information about the Python-list mailing list