Python recursive function question

Randall Hopper aa8vb at yahoo.com
Mon Aug 28 07:28:29 EDT 2000


     I was coding up a non-iterative (completely recursive) insertion sort
in Python for a class assignment, and hit an interesting syntactic quirk I
didn't know about.  And I don't understand why it won't work.

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

       ...

       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.

"Python does not have arbitrarily nested scopes" doesn't invoke enough data
structures for me to understand what's really going on in the interpreter.
How is interpreter compilation of InsertionSort() fundamentally different
than compilation of Insert().

Any clarifications would be appreciated.

Thanks,

-- 
Randall Hopper
aa8vb at yahoo.com




More information about the Python-list mailing list