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.
This commit is contained in:
Guido van Rossum 1998-08-07 17:45:09 +00:00
parent 1a0b872665
commit aee5e26f4b
1 changed files with 39 additions and 0 deletions

View File

@ -1186,6 +1186,39 @@ f()
will print \code{5}. will print \code{5}.
\strong{Important warning:} The default value is evaluated only once.
This makes a difference when the default is a mutable object such as a
list or dictionary. For example, the following function accumulates
the arguments passed to it on subsequent calls:
\begin{verbatim}
def f(a, l = []):
l.append(a)
return a
print f(1)
print f(2)
print f(3)
\end{verbatim}
This will print
\begin{verbatim}
[1]
[1, 2]
[1, 2, 3]
\end{verbatim}
If you don't want the default to be shared between subsequent calls,
you can write the function like this instead:
\begin{verbatim}
def f(a, l = None):
if l is None:
l = []
l.append(a)
return a
\end{verbatim}
\subsection{Keyword Arguments} \subsection{Keyword Arguments}
\label{keywordArgs} \label{keywordArgs}
@ -1574,6 +1607,7 @@ number of elements as the length of the tuple. Note that multiple
assignment is really just a combination of tuple packing and tuple assignment is really just a combination of tuple packing and tuple
unpacking! unpacking!
% XXX This is no longer necessary!
Occasionally, the corresponding operation on lists is useful: \emph{list Occasionally, the corresponding operation on lists is useful: \emph{list
unpacking}. This is supported by enclosing the list of variables in unpacking}. This is supported by enclosing the list of variables in
square brackets: square brackets:
@ -1583,6 +1617,9 @@ square brackets:
>>> [a1, a2, a3, a4] = a >>> [a1, a2, a3, a4] = a
\end{verbatim} \end{verbatim}
% XXX Add a bit on the difference between tuples and lists.
% XXX Also explain that a tuple can *contain* a mutable object!
\section{Dictionaries} \section{Dictionaries}
\label{dictionaries} \label{dictionaries}
@ -1858,6 +1895,8 @@ This imports all names except those beginning with an underscore
\subsection{The Module Search Path} \subsection{The Module Search Path}
\label{searchPath} \label{searchPath}
% XXX Need to document that a lone .pyc/.pyo is acceptable too!
\indexiii{module}{search}{path} \indexiii{module}{search}{path}
When a module named \module{spam} is imported, the interpreter searches When a module named \module{spam} is imported, the interpreter searches
for a file named \file{spam.py} in the current directory, for a file named \file{spam.py} in the current directory,