How about some syntactic sugar for " __name__ == '__main__' "?

Roy Smith roy at panix.com
Thu Nov 13 08:33:30 EST 2014


In article <mailman.15769.1415869145.18130.python-list at python.org>,
 Chris Angelico <rosuav at gmail.com> wrote:

> On Thu, Nov 13, 2014 at 7:47 PM, Cameron Simpson <cs at zip.com.au> wrote:
> > My view is that if there's a main (i.e. the module implements a small app
> > all on its own, however tiny), then the main program logic should come
> > first. The details follow later.
> 
> Ah, I see. Makes sense. It's kinda like an executable docstring. Still
> not my preferred style, but makes its own sense.
> 
> ChrisA

I generally define a main() routine up near the top, then put

if __name__ == '__main__':
    main()

at the bottom.  That gives you the best of both worlds; you get to see 
the main() code up front in the file, but you also get to not worry 
about what order things are defined.

It also means you can import your module and call its main() directly.  
That's useful for testing, but occasionally for other purposes too.  You 
can't do that with the (detestable) style of putting a whole bunch of 
code in the body of the "if" statement.



More information about the Python-list mailing list