if __name__ == "__main__"

Steve Holden sholden at holdenweb.com
Fri Dec 21 12:15:09 EST 2001


"Martin von Loewis" <loewis at informatik.hu-berlin.de> wrote in message
news:j4ofkso7e1.fsf at informatik.hu-berlin.de...
> crennert at pbmplus.com (Chris Rennert) writes:
>
> > Could someone please fill me in on how the if __name__ == "__main__
> > thing works.  I am reading through some tutorials and I never really
> > get a clear definitive answer on that.
> > Is this like main() in C?
>
> No. __name__, on module level, is the name of the module. So if you
> would modify urllib.py to contain
>
> print __name__
>
> then "import urllib" would print
>
> urllib
>
> Now, the file that you pass on the command line of the interpreter
> does not have a module name (because it really isn't a module), so
> __name__ is set to the string "__main__" inside that code. That allows
> you to write a file that is used both as a module and as a program.
>
Everything Martin wrote is correct, but the first word might be considered
somewhat harsh!

In C, you identify the program's entry point by defining a main() function,
which is called when program execution starts. In Python, when program
execution starts the interpreter identifies the main program by setting its
module name to "__main__".

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list