This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: if __name__=='__main__' missing in tutorial
Type: enhancement Stage:
Components: Documentation Versions:
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, ggenellina, sonderblade
Priority: normal Keywords:

Created on 2007-01-17 05:11 by ggenellina, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg54988 - (view) Author: Gabriel Genellina (ggenellina) Date: 2007-01-17 05:11
I could not find any reference to the big idiom:

if __name__=="__main__":
    xxx()

inside the Python tutorial. Of course it is documented in the Library Reference and the Reference Manual, but such an important idiom should be on the Tutorial for beginners to see.

I can't provide a patch, and English is not my native language, but I think a short text like the following would suffice (in section More on Modules, before the paragraph "Modules can import other modules..."):


Sometimes it is convenient to invoke a module as it were a script, either for testing purposes, or to provide a convenient user interfase to the functions contained in the module. But you don't want to run such code when the module is imported into another program, only when it's used as a standalone script. The way of differentiate both cases is checking the \code{__name__} attribute: as seen on the previous section, it usually holds the module name, but when the module is invoked directly, it's always \samp{__main__} regardless of the script name.

Add this at the end of \file{fibo.py}:

\begin{verbatim}
if __name__=="__main__":
    import sys
    fib(int(sys.argv[1]))
\end{verbatim}

and then you can execute it using:

\begin{verbatim}
python fibo.py 50
1 1 2 3 5 8 13 21 34
\end{verbatim}

msg54989 - (view) Author: Björn Lindqvist (sonderblade) Date: 2007-07-10 11:10
I just ran into this "problem" today, when teaching someone python. It is definitely a glaring omission and needs to be fixed.
msg54990 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2007-07-12 09:38
Added a section about this in rev. 56306, 56307 (2.5).
History
Date User Action Args
2022-04-11 14:56:22adminsetgithub: 44480
2007-01-17 05:11:04ggenellinacreate