[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)

Cameron Simpson cs at zip.com.au
Mon Nov 25 08:19:32 CET 2013


On 24Nov2013 17:26, Philipp A. <flying-sheep at web.de> wrote:
> i’m all for a special method name or decorator, because of the namespace
> issue.
> 
> once you do more on your main function than print(‘Hello World’), say
> define variables, you tend to do:
> 
> def main():
>     ...
> if __name__ == '__main__':
>     main()
> 
> in order not to pollute the namespace of the module.
[...]

This is what I do, almost word for word. When I do this, the main()
function is the first function in the module and the code at the
bottom goes:

  if __name__ == '__main__':
      import sys
      sys.exit(main(sys.argv))

This make the main() function obvious when looking at the code, and makes
things work intuitively on the command line, with a meaningful exit status.

Modules without a main() run unit tests and I have an aspirational goal to
fold a selftest mode into the module with a main().

A magic name? It seems a little overkill if the code is written in a fashion
like the above: the main() is obvious.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

SCCS, the source motel!  Programs check in and never check out! - Ken Thompson


More information about the Python-ideas mailing list