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

Skip to content

Commit e039439

Browse files
committed
Clarify evaluation of default arguments at def time with more text and
an example.
1 parent c6e2290 commit e039439

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

Doc/ref/ref7.tex

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,8 +304,7 @@ \section{Function definitions\label{function}}
304304

305305
When one or more top-level parameters have the form \var{parameter}
306306
\code{=} \var{expression}, the function is said to have ``default
307-
parameter values.'' \strong{Default parameter values are evaluated
308-
when the function definition is executed.} For a parameter with a
307+
parameter values.'' For a parameter with a
309308
default value, the corresponding argument may be omitted from a call,
310309
in which case the parameter's default value is substituted. If a
311310
parameter has a default value, all following parameters must also have
@@ -315,6 +314,25 @@ \section{Function definitions\label{function}}
315314
\code{def f(a=1, b)} is interpreted as \code{def f(a=1, b=None)}.}
316315
\indexiii{default}{parameter}{value}
317316

317+
\strong{Default parameter values are evaluated when the function
318+
definition is executed.} This means that the expression is evaluated
319+
once, when the function is defined, and that that same
320+
``pre-computed'' value is used for each call. This is especially
321+
important to understand when a default parameter is a mutable object,
322+
such as a list or a dictionary: if the function modifies the object
323+
(e.g. by appending an item to a list), the default value is in effect
324+
modified. This is generally not what was intended. A way around this
325+
is to use \code{None} as the default, and explicitly test for it in
326+
the body of the function, e.g.:
327+
328+
\begin{verbatim}
329+
def whats_on_the_telly(penguin=None):
330+
if penguin is None:
331+
penguin = []
332+
penguin.append("property of the zoo")
333+
return penguin
334+
\end{verbatim}
335+
318336
Function call semantics are described in more detail in section
319337
\ref{calls}.
320338
A function call always assigns values to all parameters mentioned in

0 commit comments

Comments
 (0)