why a main() function?

Steven Bethard steven.bethard at gmail.com
Tue Sep 19 11:15:58 EDT 2006


Steve Holden 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
>>
>> def main():
>>     print "hi"
>>
>> main()
>>
>> instead of
>>
>> print "hi"
>>
>> What are the advantages of doing this?
>>
> Guido van Rossum himself can tell you:
> 
>   http://www.artima.com/forums/flat.jsp?forum=106&thread=4829

Interesting.  A lot of the suggestions he makes are unnecessary if you 
use argparse_ or optparse, since they do much cleaner argument parsing 
and error reporting.

I basically never write a main() function in the sense described here. 
My code usually looks something like:

     if __name__ == '__main__':
         parser = _argparse.ArgumentParser(...)
         parser.add_argument(...)
         ...
         arguments = parser.parse_args()

         function_that_actually_does_stuff(arguments.foo,
                                           arguments.bar,
                                           arguments.baz)

So my ``if __name__ == '__main__'`` block does just enough argument 
parsing to be able to call a real function.

.. _argparse: http://argparse.python-hosting.com/

STeVe



More information about the Python-list mailing list