Recursive inner function... How?
Fredrik Lundh
fredrik at effbot.org
Mon Jan 1 18:01:33 EST 2001
hi bjorn,
> > 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()
>
> 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?)
Close enough: the global statement doesn't modify the
global namespace, it just tells Python's compiler that
"inner" is a global name.
The compiler uses that information to generate the right
bytecode operations: LOAD/STORE_FAST for locals,
LOAD/STORE_GLOBAL for globals.
(this only applies to the code in "outer", though -- inside
"inner", "inner" is a global name... the recursive call only
works because "outer" creates the global variable before
it makes the call...)
</F>
More information about the Python-list
mailing list