summaryrefslogtreecommitdiffstats
path: root/Doc/ref
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>1998-12-04 19:37:10 (GMT)
committerGuido van Rossum <guido@python.org>1998-12-04 19:37:10 (GMT)
commite039439e3bb91fec32cc161018e40aaf27bf0211 (patch)
tree4dfaf397d5ec9c5dde030b55038d3c14bef4945f /Doc/ref
parentc6e22902adb34488c80a644cb3ac91e07cd1eaad (diff)
downloadcpython-e039439e3bb91fec32cc161018e40aaf27bf0211.zip
cpython-e039439e3bb91fec32cc161018e40aaf27bf0211.tar.gz
cpython-e039439e3bb91fec32cc161018e40aaf27bf0211.tar.bz2
Clarify evaluation of default arguments at def time with more text and
an example.
Diffstat (limited to 'Doc/ref')
-rw-r--r--Doc/ref/ref7.tex22
1 files changed, 20 insertions, 2 deletions
diff --git a/Doc/ref/ref7.tex b/Doc/ref/ref7.tex
index cacd8ef..bfceeea 100644
--- a/Doc/ref/ref7.tex
+++ b/Doc/ref/ref7.tex
@@ -304,8 +304,7 @@ executed only when the function is called.
When one or more top-level parameters have the form \var{parameter}
\code{=} \var{expression}, the function is said to have ``default
-parameter values.'' \strong{Default parameter values are evaluated
-when the function definition is executed.} For a parameter with a
+parameter values.'' For a parameter with a
default value, the corresponding argument may be omitted from a call,
in which case the parameter's default value is substituted. If a
parameter has a default value, all following parameters must also have
@@ -315,6 +314,25 @@ expressed by the grammar.%
\code{def f(a=1, b)} is interpreted as \code{def f(a=1, b=None)}.}
\indexiii{default}{parameter}{value}
+\strong{Default parameter values are evaluated when the function
+definition is executed.} This means that the expression is evaluated
+once, when the function is defined, and that that same
+``pre-computed'' value is used for each call. This is especially
+important to understand when a default parameter is a mutable object,
+such as a list or a dictionary: if the function modifies the object
+(e.g. by appending an item to a list), the default value is in effect
+modified. This is generally not what was intended. A way around this
+is to use \code{None} as the default, and explicitly test for it in
+the body of the function, e.g.:
+
+\begin{verbatim}
+def whats_on_the_telly(penguin=None):
+ if penguin is None:
+ penguin = []
+ penguin.append("property of the zoo")
+ return penguin
+\end{verbatim}
+
Function call semantics are described in more detail in section
\ref{calls}.
A function call always assigns values to all parameters mentioned in