[Tutor] function declaration problems perhaps?

Dave Kuhlman dkuhlman at rexx.com
Wed Jul 25 20:35:53 CEST 2007

On Wed, Jul 25, 2007 at 06:21:08PM +0100, Alan Gauld wrote:
> I'm not sure if the undefined name errors come from the compilation
> or from the execution - does anyone else. I confess i've never looked
> deeply into how Python actually does its complile/execute cycle.

A couple of points that might help:

1. In python it's all execution.  Yes, Kent is right that Python is
   compiled to byte code.  But, Alan is right to ignore that in
   trying to understand what happens.  In particular, "class" and
   "def" statements execute, and when they do they bind a name to a
   class or function object in the local namespace.

2. It's all about look-up.  Every variable reference causes Python
   to do a look-up in the current namespace (and enclosing
   namespaces, which is another subject).  So, you need to ask
   whether at that time a given name has been created in the
   current namespace.

Some examples ...

The following works because func2 is not called (looked up) until
func1 is executed, which is after func2 is defined:

    # Test 1

    def func1():

    def func2():
        print 'hello'


The following does *not* work, because func1 executes *before*
func2 is defined, which means that func2 is needed before it is

    # Test 2

    def func1():


    def func2():
        print 'hello'

And, (admittedly a rare case), the following does *not* work
because when the statement "class A(B)" executes, B is not yet
defined and is needed.  This is an example of a name (B) being
needed when another object (A) is defined (when the "class A(B)" is

    # Test 3

    class A(B):

    class B(object):

By the way, this is an important and fundamental subject about
Python.  When I teach classes on Python, I always need to explain
Python's execution model, and I always struggle with it.  So,
anything you can tell me that would help me teach this will be much


Dave Kuhlman

More information about the Tutor mailing list