23

Should I start a Python program with:

if__name__ == '__main__':
some code...

And if so, why? I saw it many times but don't have a clue about it.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
Kirill Titov
  • 2,060
  • 5
  • 21
  • 33
  • @Kirill Titov: Please don't edit the question to say "Closed". It isn't closed. You selected an answer -- that's perfect, and all you ever need to do. Doing more is confusing. – S.Lott Nov 13 '08 at 16:38

4 Answers4

30

If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, __name__ evaluates to 'foo', but if you run "python foo.py" from the command line, __name__ evaluates to '__main__'.

Note that you do need to insert a space between if and _, and indent the main program:

if __name__ == '__main__':
    main program here
Jouni K. Seppänen
  • 43,139
  • 5
  • 71
  • 100
  • 1
    +1: Reuse is important. A module can have 2 lives. As main program. As component in some other main program. As main program is DOES things. As component, it merely defines things. – S.Lott Nov 13 '08 at 15:41
  • This may go without saying, but be sure that this conditional goes at the end of your file. – Jeremy Cantrell Nov 14 '08 at 00:51
25

A better pattern is this:

def main():
   ...

if __name__ == '__main__':
   main()

This allows your code to be invoked by someone who imported it, while also making programs such as pychecker and pylint work.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • thank you! i was worried that the whole program had to be indented from the get go. I didin't like that. – J.J. Nov 13 '08 at 16:40
22

Guido Van Rossum suggests:

def main(argv=None):
  if argv is None:
    argv = sys.argv
  ...

if __name__ == "__main__":
    sys.exit(main())

This way you can run main() from somewhere else (supplying the arguments), and if you want to exit with an error code just return 1 from main(), and it won't make an interactive interpreter exit by mistake.

orip
  • 73,323
  • 21
  • 116
  • 148
3

This is good practice. First, it clearly marks your module entry point (assuming you don't have any other executable code at toplevel - yuck). Second, it makes your module importable by other modules without executing, which some tools like code checkers, packagers etc. need to do.

Rafał Dowgird
  • 43,216
  • 11
  • 77
  • 90