Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit aee5e26

Browse files
committed
Add warning that mutable argument defaults are evaluated only once;
with examples and workaround. This keeps coming up, and I believe that this section in the tutorial may have been (in part) the source of the confusion. While it didn't show examples with [] for a default, it also didn't emphasize enough why that would be a bad idea, and while it did say that defaults are evaluated at the point of function definition, the example was not relevant for this issue.
1 parent 1a0b872 commit aee5e26

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Doc/tut/tut.tex

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1186,6 +1186,39 @@ \subsection{Default Argument Values}
11861186

11871187
will print \code{5}.
11881188

1189+
\strong{Important warning:} The default value is evaluated only once.
1190+
This makes a difference when the default is a mutable object such as a
1191+
list or dictionary. For example, the following function accumulates
1192+
the arguments passed to it on subsequent calls:
1193+
1194+
\begin{verbatim}
1195+
def f(a, l = []):
1196+
l.append(a)
1197+
return a
1198+
print f(1)
1199+
print f(2)
1200+
print f(3)
1201+
\end{verbatim}
1202+
1203+
This will print
1204+
1205+
\begin{verbatim}
1206+
[1]
1207+
[1, 2]
1208+
[1, 2, 3]
1209+
\end{verbatim}
1210+
1211+
If you don't want the default to be shared between subsequent calls,
1212+
you can write the function like this instead:
1213+
1214+
\begin{verbatim}
1215+
def f(a, l = None):
1216+
if l is None:
1217+
l = []
1218+
l.append(a)
1219+
return a
1220+
\end{verbatim}
1221+
11891222
\subsection{Keyword Arguments}
11901223
\label{keywordArgs}
11911224

@@ -1574,6 +1607,7 @@ \section{Tuples and Sequences}
15741607
assignment is really just a combination of tuple packing and tuple
15751608
unpacking!
15761609

1610+
% XXX This is no longer necessary!
15771611
Occasionally, the corresponding operation on lists is useful: \emph{list
15781612
unpacking}. This is supported by enclosing the list of variables in
15791613
square brackets:
@@ -1583,6 +1617,9 @@ \section{Tuples and Sequences}
15831617
>>> [a1, a2, a3, a4] = a
15841618
\end{verbatim}
15851619

1620+
% XXX Add a bit on the difference between tuples and lists.
1621+
% XXX Also explain that a tuple can *contain* a mutable object!
1622+
15861623
\section{Dictionaries}
15871624
\label{dictionaries}
15881625

@@ -1858,6 +1895,8 @@ \section{More on Modules}
18581895
\subsection{The Module Search Path}
18591896
\label{searchPath}
18601897

1898+
% XXX Need to document that a lone .pyc/.pyo is acceptable too!
1899+
18611900
\indexiii{module}{search}{path}
18621901
When a module named \module{spam} is imported, the interpreter searches
18631902
for a file named \file{spam.py} in the current directory,

0 commit comments

Comments
 (0)