[Tutor] function declaration problems perhaps?

Kent Johnson kent37 at tds.net
Wed Jul 25 13:27:28 CEST 2007

Alan Gauld wrote:
> "nibudh" <nibudh at gmail.com> wrote
>> I looked over my code (all 41 lines!) and couldn't find anything, 
>> then on a
>> hunch i moved the def statement _above_ the rest of my code and hey 
>> presto
>> it worked.
>> I vaguely understand why this is happening, but can someone explain 
>> it to
>> me.
> Its pretty simple.
> Python processes the file top to bottom. If it comes upon
> a name that it doesn't recofgnise it generates an error.

A key concept to understand is that def (and class and import) are 
executable statements that have no effect until they are actually 
executed. The effect of executing a def is to create a function object 
and bind it to the name given in the def. Before the def is executed, 
the name is not bound to anything and can't be used.

This is a shift from less-dynamic languages such as Java and C, where 
functions exist from the time a module is loaded.

One consequence of executable def is that you can, for example, have 
conditional defs:
if has_foo:
   def bar():
     # Implementation of bar using foo
   def bar():
     # Implementation of bar without using foo

Similar techniques can be used with imports. This can be handy for 
writing code that is backwards compatible. For example here is some code 
that tries to import ElementTree from its Python 2.5 library package and 
from the effbot distribution:

     import xml.etree.ElementTree as ET # in python >=2.5
except ImportError:
         import elementtree.ElementTree as ET # effbot's pure Python module
     except ImportError:
         raise ImportError("Can't import ElementTree")

If this code successfully executes, the ElementTree module will be 
available as ET.


More information about the Tutor mailing list