vertical ordering of functions

Ben Finney ben+python at benfinney.id.au
Tue May 3 19:58:45 EDT 2011


Jabba Laci <jabba.laci at gmail.com> writes:

> Is there a convention for this? Should main() be at the top and called
> function below?

No, it's Python convention for both of those to be at the end of the
module.

I follow the convention described by Guido van Rossum in
<URL:http://www.artima.com/weblogs/viewpost.jsp?thread=4829>.

Essentially, the mainline code is all in a top-level function, which
accepts command-line arguments in its ‘argv’ parameter, catches any
‘SystemExit’ exception, and returns the exit code for the program.

The ‘if __name__ == "__main__"’ section does nothing but call that
function, passing the ‘sys.argv’ value, then exit with the return value.

This makes the whole behaviour of the program available for calling as a
function, while the program works as expected when invoked as a program.

Commonly I will name the function ‘__main__’, but this is an artefact of
my previously-held vain hope that this idiom would become special to
Python and called automatically without the ‘if __name__ …’ hack. Guido,
and most others I've seen use this idiom, simply name the function
‘main’.

-- 
 \       “An idea isn't responsible for the people who believe in it.” |
  `\                                      —Donald Robert Perry Marquis |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list