python __main__ is similar to java main()

Sean 'Shaleh' Perry shalehperry at attbi.com
Wed Jun 19 13:50:12 EDT 2002


On 19-Jun-2002 David Nunes wrote:
> Well I've read the docs and searched in the newsgroup archives but
> I'm still confused about __main__
> 
>         I  expected it to startup the program, like main in java but
> when I feed it to the interpreter he just "eats" the file loads wathever
> is in the file but doesn't run main.
> 
>         So am I suposed to explicitly call it like in the file below or is
> there a better (pythonic) way to do it??
> 

the idiom is this:

class MyClass:
  pass

if __name__ == '__main__':
  # do stuff with MyClass

what is happening here is __name__ is defined to be the name of the module when
the file is called via 'import' or 'from' or it is called '__main__' if being
used as a script and called directly by the interpreter.  Note __name__ is at
the module scope, not part of any class.

This allows for each module to have test code in it that can be executed easily.

If you are simply writing a #!python style script there is no need for main,
the interpreter starts at the first line and executes everything it sees.





More information about the Python-list mailing list