newbie questions

Duncan Booth duncan.booth at invalid.invalid
Wed Mar 15 11:39:33 EST 2006


meeper34 wrote:

> 4.  Really basic question, and I'm sure I will learn this very quickly
> with more reading, but I'm confused by the lack of an entry point in a
> Python app, i.e. int main().

Keir's answer about testing for __main__ is good, but it might also help 
you to think a bit about what it actually means to run a Python program.

Python executes code line by line from top to bottom. Almost every 
statement in Python is executed.

This is quite different from a language like C where executable statements 
are safely tucked inside functions and execution starts at an arbitrary 
point (the 'main' function), or even C++ where global and static variable 
initialisations are also executable. In Python everything except the 
'global' statement is executed at runtime (also comments and docstrings 
don't execute). That includes 'import', 'class' and 'def'.

So, when you run a Python script it starts on the first line of the script. 
Usually that will be an 'import', so the interpreter will go off and find 
the referenced module, compile it if required, and then execute the module 
from top to bottom. If a module is imported more than once, it only starts 
executing the code in that module on the first import, and if you have 
circular imports you can end up accessing a module which has only partly 
executed.

When it sees a class definition the interpreter executes its body in a new 
namespace and uses the result to create the class. When it sees a function 
definition it doesn't execute the body, but it does execute any default 
arguments and then it creates the function.

What does this mean in practice? You cannot reference a class or function 
until after you have executed the relevant definition. You can stick a 
function definition inside a loop if you want: the name just gets rebound 
to a new object each time it is executed. The behaviour can be quite 
suprising at times for people who think of declaring functions, but it is 
extremely logical if you remember that everything has to execute.

The __name__=='__main__' convention works because the main script executes 
in the module called '__main__', whereas every other module executes under 
its own name. But it isn't really the start of the program: rather it is 
the very last thing executed after all the modules have imported and done 
whatever initialisation they want, and after all the classes and functions 
have been defined.



More information about the Python-list mailing list