Python recursive function question

Jeremy Hylton jeremy at alum.mit.edu
Mon Aug 28 09:41:40 EDT 2000


In article <20000828072829.A957771 at vislab.epa.gov>,
  Randall Hopper <aa8vb at yahoo.com> wrote:

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

The scopes refer to namespaces in which names are resolved.  To resolve
the name "Insert," Python looks in the current namespaces, the global
namespace, and the builtin namespace.  If your recursive function is
defined at what you called file level, it is part of the module's global
namespace.  When the recursive call occurs inside the function, Python
first looks in the local namespace (and does not find it).  Then it
looks in the global namespace and finds it.

When you define a recursive function in another scope, e.g. inside
another function or method, it does not create an entry in the global
namespace.  Thus, Python can not find a binding for the name and raises
a NameError.

--
-- Jeremy Hylton, <http://www.python.org/~jeremy/>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list