why a main() function?

Duncan Booth duncan.booth at invalid.invalid
Wed Sep 20 04:23:27 EDT 2006


anton.list at gmail.com wrote:

> beliavsky at aol.com wrote:
>> I think I read a suggestion somewhere to wrap the code where a Python
>> script starts in a main() function, so one has
> 
><snip>
> 
>> What are the advantages of doing this?
> 
> Others have stated all the good ones, so I'll state a slightly dumber
> one for us part time amateur hackers :)
> 
> If you start off writing all your python module inside a main function
> then as you chop your code up into other functions (refactoring), the
> code inside main is already at the proper indentation level for the new
> top level functions. No more indenting it one level further to  suit
> the functions indentation.
> 
That is also true if you start by putting all the main code inside an 'if 
__name__=="__main__":' block. Besides, how hard is it to select the code 
and hit tab or whatever the 'indent region' command is in your editor?

FWIW, my scripts generally evolve through several stages.

So looking at one I wrote recently I see that it started with a few lines 
at the outer level which quickly went inside a __name__=='__main__' block 
(so I could prod functions in the script interactively). Then as it grew 
larger the script moved into a main() function and some argument processing 
appeared in the __main__ block (and all the support functions disappeared 
into a separate module). Then I wanted some exception handling at the outer 
level so now I have the __main__ block containing outer level exception 
handling, and calling main() which does argument processing and calls 
script() which contains the original script.

It may evolve further: main() is a bit too large at the moment, and I think 
I want to move the original script into another module with a command line 
argument to select between scripts. My point being that I don't have a hard 
and fast rule: I do whatever seems to make the code read clearly at the 
time.



More information about the Python-list mailing list