__main__ : What is this?

Matimus mccredie at gmail.com
Fri Oct 19 20:26:22 EDT 2007


> I've read various portions of the Python 2.5 documentation in an
> attempt to figure out exactly what the following condition represents:
>
> if __name__ == "__main__":
>     main()
>
> However, I was not able to determine what it is actually checking for.
> Could someone point me in the way of a tutorial or explain this for
> me? Thanks.

__name__ is an attribute on a module that shows the standard name for
that module:

>>> import sys
>>> sys.__name__
'sys'

The name stays constant even if you do something funny during import:

>>> import os as something_else
>>> something_else.__name__
'os'

When using the interpreter or running a python script code will be
executed in a standard module called "__main__".

>>> __name__
'__main__'

In fact, you can even import __main__ if you want:

>>> import __main__
>>> __main__.__name__
'__main__'
>>> a = 100
>>> __main__.a
100

The common pattern:

if __name__ == "__main__":
  # do stuff

IMHO better written:

if "__main__" == __name__:
    # do stuff

Allows a module to selectively run code only if it is being run as a
program. That code will not run if it is imported as a module, because
in that condition __name__ will return the name of the file (sans .py)
that the code is in. I've never tried naming a file __main__.py and
importing it, my guess is that you shouldn't do that :).

Matt




More information about the Python-list mailing list