about if __name == '__main__':

Ian Kelly ian.g.kelly at gmail.com
Sun Aug 28 12:51:32 EDT 2011


On Sun, Aug 28, 2011 at 9:34 AM, Amit Jaluf <amitjaluf at gmail.com> wrote:
> hello group
>
> i have one question about this
>
> if __name == '__main__':

First, it should be:

if __name__ == '__main__':

> is it same as other languages like[c,c++]  main function. because of i
> google and read faqs
> and also " http://docs.python.org/faq/programming#how-do-i-find-the-current-module-name"
> this and i am confused.

No, that is not a main function.  It's not even a function.  When
Python runs a script, it loads that script as a module, sets its name
to be __main__, and then executes the entire module, starting from the
top as normal.  What that if statement defines is an ordinary branch
that is only executed if the current module is the main module, as
opposed to having been imported from some other module.  Normally this
will be at the end of the file so that all the definitions in the file
will have already been executed.

The usual idiom for this is:

def main(argv):
    # parse arguments and begin program logic...
    pass

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

This is also frequently used for unit testing of library modules, so
that the module can be tested just by running it.

# define library classes and functions here

if __name__ == '__main__':
    # perform unit tests

Cheers,
Ian



More information about the Python-list mailing list