Python recursive function question

Johann Hibschman johann at physics.berkeley.edu
Mon Aug 28 16:34:57 EDT 2000


Randall Hopper writes:


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

Okay, here's my shot at this.

Imagine "def Insert(...): ..." as really saying "Insert = <some
function>."  It's no different than saying:

g = "I'm a global!"
def outer():
    a = 10
    def inner():
      b = 20
      print a

Which leads to an error.  The innards of 'inner' cannot see the 'a'
defined in outer, because 'inner' has only two places to put
variables: its own local scope (where 'b' is defined) and the
global/module scope (where 'g' is defined).  It can't access 'a',
because that's in the local scope of 'outer'.

You are thinking of 'def' as being more magical than it is, I think.
All it does is introduce a name into the local namespace and bind a
function object to it.

What you said was, borrowing a fake non-python syntax,

InsertionSort = function(...):   # f1
    Insert = function(...):      # f2
        ...
        Insert()
    ...

The call of 'Insert' tries to look up 'Insert' in the local bindings
of f2, where it isn't defined, and then tried the global namespace,
where it still isn't defined, and then fails.  Insert is only defined
in the local bindings of f1, where the function object f2 can't get to
it.

I hope that helps.

-- 
Johann Hibschman                           johann at physics.berkeley.edu



More information about the Python-list mailing list