What is "__name__" and ......

Steve Holden sholden at holdenweb.com
Wed Mar 5 14:53:40 CET 2003


"Erik Max Francis" <max at alcyone.com> wrote in message
news:3E618A06.B2C5D094 at alcyone.com...
> 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.
>

While everything Erik Max writes is true, I think he did you a disservice
using a module whose __name__ is "name" and then showing you that when you
run it, it's name is "__main__". But it's true!

works-just-as-well-with-a-module-called-sample.py-ly y'rs  - steve
--
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Register for PyCon now!            http://www.python.org/pycon/reg.html







More information about the Python-list mailing list