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(): func2() def func2(): print 'hello' func1() The following does *not* work, because func1 executes *before* func2 is defined, which means that func2 is needed before it is defined: # Test 2 def func1(): func2() 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 executed): # Test 3 class A(B): pass class B(object): pass 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 appreciated. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor