[ python-Feature Requests-1637365 ] if __name__=='__main__' missing in tutorial
SourceForge.net
noreply at sourceforge.net
Thu Jul 12 11:38:08 CEST 2007
Feature Requests item #1637365, was opened at 2007-01-17 05:11
Message generated for change (Comment added) made by gbrandl
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=1637365&group_id=5470
Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: None
>Status: Closed
>Resolution: Fixed
Priority: 5
Private: No
Submitted By: Gabriel Genellina (gagenellina)
Assigned to: Nobody/Anonymous (nobody)
Summary: if __name__=='__main__' missing in tutorial
Initial Comment:
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}
----------------------------------------------------------------------
>Comment By: Georg Brandl (gbrandl)
Date: 2007-07-12 09:38
Message:
Logged In: YES
user_id=849994
Originator: NO
Added a section about this in rev. 56306, 56307 (2.5).
----------------------------------------------------------------------
Comment By: Björn Lindqvist (sonderblade)
Date: 2007-07-10 11:10
Message:
Logged In: YES
user_id=51702
Originator: NO
I just ran into this "problem" today, when teaching someone python. It is
definitely a glaring omission and needs to be fixed.
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=1637365&group_id=5470
More information about the Python-bugs-list
mailing list