What is "__name__" and ......
Erik Max Francis
max at alcyone.com
Sat Mar 1 23:35:18 EST 2003
Alonde wrote:
> I don't understand "__name__" and "__main__" and
> everything between the __ and __
>
> What does
>
> if __name == "__main__":
__name__ is the name of the current module. If this is equal to the
string "__main__" then the module is being executed directly; otherwise
it's being imported.
Watch:
max at oxygen:~/tmp% cat > name.py
print __name__
^D
max at oxygen:~/tmp% python name.py # run the script directly
__main__
max at oxygen:~/tmp% python
Python 2.2.2 (#2, Oct 14 2002, 17:32:20)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import name # import it
name
>>>
So the canonical
if __name__ == '__main__': ...
test is to see whether the script is being executed directly instead of
imported.
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ The perfection of innocence, indeed, is madness.
\__/ Arthur Miller
7 Sisters Productions / http://www.7sisters.com/
Web design for the future.
More information about the Python-list
mailing list