[ python-Feature Requests-1637365 ] if __name__=='__main__' missing in tutorial

SourceForge.net noreply at sourceforge.net
Wed Jan 17 06:11:05 CET 2007


Feature Requests item #1637365, was opened at 2007-01-17 02:11
Message generated for change (Tracker Item Submitted) made by Item Submitter
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: Open
Resolution: None
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}



----------------------------------------------------------------------

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