Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12346

Re: about if __name == '__main__':

References <c0025c7f-8fb1-4be6-a41b-6227aa388a53@h23g2000pra.googlegroups.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-08-28 10:51 -0600
Subject Re: about if __name == '__main__':
Newsgroups comp.lang.python
Message-ID <mailman.509.1314550323.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Aug 28, 2011 at 9:34 AM, Amit Jaluf <amitjaluf@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

about  if __name == '__main__': Amit Jaluf <amitjaluf@gmail.com> - 2011-08-28 08:34 -0700
  Re: about if __name == '__main__': Ian Kelly <ian.g.kelly@gmail.com> - 2011-08-28 10:51 -0600
    Re: about if __name == '__main__': woooee <woooee@gmail.com> - 2011-08-28 11:56 -0700
      Re: about if __name == '__main__': Terry Reedy <tjreedy@udel.edu> - 2011-08-28 17:35 -0400
      Re: about if __name == '__main__': Ian Kelly <ian.g.kelly@gmail.com> - 2011-08-28 17:55 -0600
      Re: about if __name == '__main__': Cameron Simpson <cs@zip.com.au> - 2011-08-29 09:59 +1000
    Re: about if __name == '__main__': Amit Jaluf <amitjaluf@gmail.com> - 2011-08-28 20:42 -0700

csiph-web