Python recursive function question

Calvelo Daniel dcalvelo at pharion.univ-lille2.fr
Mon Aug 28 09:15:01 EDT 2000


Randall Hopper <aa8vb at yahoo.com> wrote:

:      First, if you define a single recursive function A defined at file
: scope, it can call itself as expected; but if you have a helper function B
: defined in A, B "cannot" call itself.  You apparently have to move it to
: file scope:
:
:      def InsertionSort(...):
:
:        def Insert(...):
:          ...
:          Insert(...)

At this point, 'Insert' is not defined. The current scope is global+local;
Insert is not yet into local scope (it will be at the end of the declaration)
and it is not into global scope (the "file" scope you refer to). 

You have the same problem if you define two functions inside ia third and 
one of the former tries to call the other.

:        ...
:
:        InsertionSort2(...)
:        ...
:        Insert(...)
:        ...
:
: FAQ entry 6.11 and 4.5 state the question I have, but rather than explain
: why it "won't" work they just point you to what you should be doing instead.
:
: How is interpreter compilation of InsertionSort() fundamentally different
: than compilation of Insert().

It's not the compilation. It's the name lookup. "Does not have arbitrarily
nested scopes" can be understood as meaning: variables from "enclosing" scopes
are not necessarily visible from "enclosed" scopes. class declarations begin
new scopes which will be merged later with enclosing scopes, this gives the
answer to FAQ 6.11

Maybe the best documentation for this is the tutorial, chapters 4.6 and 9.2.

HTH, DCA

-- Daniel Calvelo Aros
     calvelo at lifl.fr



More information about the Python-list mailing list