blob: cfafc74d99083dedafa13827e04ff4a16373e6dd [file] [log] [blame]
Fred Drake61c77281998-07-28 19:34:22 +00001\chapter{Compound statements\label{compound}}
Fred Drakef6669171998-05-06 19:52:49 +00002\indexii{compound}{statement}
3
4Compound statements contain (groups of) other statements; they affect
5or control the execution of those other statements in some way. In
6general, compound statements span multiple lines, although in simple
7incarnations a whole compound statement may be contained in one line.
8
Fred Drake5c07d9b1998-05-14 19:37:06 +00009The \keyword{if}, \keyword{while} and \keyword{for} statements implement
10traditional control flow constructs. \keyword{try} specifies exception
Fred Drakef6669171998-05-06 19:52:49 +000011handlers and/or cleanup code for a group of statements. Function and
12class definitions are also syntactically compound statements.
13
Guido van Rossum5399d681998-07-24 18:51:11 +000014Compound statements consist of one or more `clauses.' A clause
15consists of a header and a `suite.' The clause headers of a
Fred Drakef6669171998-05-06 19:52:49 +000016particular compound statement are all at the same indentation level.
17Each clause header begins with a uniquely identifying keyword and ends
18with a colon. A suite is a group of statements controlled by a
19clause. A suite can be one or more semicolon-separated simple
20statements on the same line as the header, following the header's
21colon, or it can be one or more indented statements on subsequent
22lines. Only the latter form of suite can contain nested compound
23statements; the following is illegal, mostly because it wouldn't be
Fred Drake5c07d9b1998-05-14 19:37:06 +000024clear to which \keyword{if} clause a following \keyword{else} clause would
Fred Drakef6669171998-05-06 19:52:49 +000025belong:
26\index{clause}
27\index{suite}
28
29\begin{verbatim}
30if test1: if test2: print x
31\end{verbatim}
32
33Also note that the semicolon binds tighter than the colon in this
34context, so that in the following example, either all or none of the
Fred Drake5c07d9b1998-05-14 19:37:06 +000035\keyword{print} statements are executed:
Fred Drakef6669171998-05-06 19:52:49 +000036
37\begin{verbatim}
38if x < y < z: print x; print y; print z
39\end{verbatim}
40
41Summarizing:
42
Fred Drakecb4638a2001-07-06 22:49:53 +000043\begin{productionlist}
44 \production{compound_stmt}
Fred Drake53815882002-03-15 23:21:37 +000045 {\token{if_stmt}}
46 \productioncont{| \token{while_stmt}}
47 \productioncont{| \token{for_stmt}}
48 \productioncont{| \token{try_stmt}}
49 \productioncont{| \token{funcdef}}
50 \productioncont{| \token{classdef}}
Fred Drakecb4638a2001-07-06 22:49:53 +000051 \production{suite}
52 {\token{stmt_list} NEWLINE
53 | NEWLINE INDENT \token{statement}+ DEDENT}
54 \production{statement}
55 {\token{stmt_list} NEWLINE | \token{compound_stmt}}
56 \production{stmt_list}
57 {\token{simple_stmt} (";" \token{simple_stmt})* [";"]}
58\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000059
Guido van Rossum5399d681998-07-24 18:51:11 +000060Note that statements always end in a
61\code{NEWLINE}\index{NEWLINE token} possibly followed by a
62\code{DEDENT}.\index{DEDENT token} Also note that optional
63continuation clauses always begin with a keyword that cannot start a
64statement, thus there are no ambiguities (the `dangling
65\keyword{else}' problem is solved in Python by requiring nested
66\keyword{if} statements to be indented).
Fred Drakef6669171998-05-06 19:52:49 +000067\indexii{dangling}{else}
68
69The formatting of the grammar rules in the following sections places
70each clause on a separate line for clarity.
71
Fred Drake2829f1c2001-06-23 05:27:20 +000072
Fred Drake61c77281998-07-28 19:34:22 +000073\section{The \keyword{if} statement\label{if}}
Fred Drakef6669171998-05-06 19:52:49 +000074\stindex{if}
75
Fred Drake5c07d9b1998-05-14 19:37:06 +000076The \keyword{if} statement is used for conditional execution:
Fred Drakef6669171998-05-06 19:52:49 +000077
Fred Drakecb4638a2001-07-06 22:49:53 +000078\begin{productionlist}
79 \production{if_stmt}
Fred Drake53815882002-03-15 23:21:37 +000080 {"if" \token{expression} ":" \token{suite}}
81 \productioncont{( "elif" \token{expression} ":" \token{suite} )*}
82 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +000083\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000084
Guido van Rossum5399d681998-07-24 18:51:11 +000085It selects exactly one of the suites by evaluating the expressions one
Fred Drake78eb2002002-10-18 15:20:32 +000086by one until one is found to be true (see section~\ref{Booleans} for
Fred Drakef6669171998-05-06 19:52:49 +000087the definition of true and false); then that suite is executed (and no
Fred Drake5c07d9b1998-05-14 19:37:06 +000088other part of the \keyword{if} statement is executed or evaluated). If
Guido van Rossum5399d681998-07-24 18:51:11 +000089all expressions are false, the suite of the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +000090present, is executed.
91\kwindex{elif}
92\kwindex{else}
93
Fred Drake2829f1c2001-06-23 05:27:20 +000094
Fred Drake61c77281998-07-28 19:34:22 +000095\section{The \keyword{while} statement\label{while}}
Fred Drakef6669171998-05-06 19:52:49 +000096\stindex{while}
97\indexii{loop}{statement}
98
Guido van Rossum5399d681998-07-24 18:51:11 +000099The \keyword{while} statement is used for repeated execution as long
100as an expression is true:
Fred Drakef6669171998-05-06 19:52:49 +0000101
Fred Drakecb4638a2001-07-06 22:49:53 +0000102\begin{productionlist}
103 \production{while_stmt}
Fred Drake53815882002-03-15 23:21:37 +0000104 {"while" \token{expression} ":" \token{suite}}
105 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000106\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000107
Guido van Rossum5399d681998-07-24 18:51:11 +0000108This repeatedly tests the expression and, if it is true, executes the
109first suite; if the expression is false (which may be the first time it
Fred Drake5c07d9b1998-05-14 19:37:06 +0000110is tested) the suite of the \keyword{else} clause, if present, is
Fred Drakef6669171998-05-06 19:52:49 +0000111executed and the loop terminates.
112\kwindex{else}
113
Fred Drake5c07d9b1998-05-14 19:37:06 +0000114A \keyword{break} statement executed in the first suite terminates the
115loop without executing the \keyword{else} clause's suite. A
116\keyword{continue} statement executed in the first suite skips the rest
Guido van Rossum5399d681998-07-24 18:51:11 +0000117of the suite and goes back to testing the expression.
Fred Drakef6669171998-05-06 19:52:49 +0000118\stindex{break}
119\stindex{continue}
120
Fred Drake2829f1c2001-06-23 05:27:20 +0000121
Fred Drake61c77281998-07-28 19:34:22 +0000122\section{The \keyword{for} statement\label{for}}
Fred Drakef6669171998-05-06 19:52:49 +0000123\stindex{for}
124\indexii{loop}{statement}
125
Fred Drake5c07d9b1998-05-14 19:37:06 +0000126The \keyword{for} statement is used to iterate over the elements of a
Fred Drake93852ef2001-06-23 06:06:52 +0000127sequence (such as a string, tuple or list) or other iterable object:
Fred Drakef6669171998-05-06 19:52:49 +0000128\obindex{sequence}
129
Fred Drakecb4638a2001-07-06 22:49:53 +0000130\begin{productionlist}
131 \production{for_stmt}
132 {"for" \token{target_list} "in" \token{expression_list}
Fred Drake53815882002-03-15 23:21:37 +0000133 ":" \token{suite}}
134 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000135\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000136
Fred Drake7fabaf82004-11-02 19:18:20 +0000137The expression list is evaluated once; it should yield an iterable
138object. An iterator is created for the result of the
139{}\code{expression_list}. The suite is then executed once for each
140item provided by the iterator, in the
Fred Drakef6669171998-05-06 19:52:49 +0000141order of ascending indices. Each item in turn is assigned to the
142target list using the standard rules for assignments, and then the
143suite is executed. When the items are exhausted (which is immediately
Fred Drake5c07d9b1998-05-14 19:37:06 +0000144when the sequence is empty), the suite in the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +0000145present, is executed, and the loop terminates.
146\kwindex{in}
147\kwindex{else}
148\indexii{target}{list}
149
Fred Drake5c07d9b1998-05-14 19:37:06 +0000150A \keyword{break} statement executed in the first suite terminates the
151loop without executing the \keyword{else} clause's suite. A
152\keyword{continue} statement executed in the first suite skips the rest
153of the suite and continues with the next item, or with the \keyword{else}
Fred Drakef6669171998-05-06 19:52:49 +0000154clause if there was no next item.
155\stindex{break}
156\stindex{continue}
157
158The suite may assign to the variable(s) in the target list; this does
159not affect the next item assigned to it.
160
161The target list is not deleted when the loop is finished, but if the
162sequence is empty, it will not have been assigned to at all by the
Guido van Rossum5399d681998-07-24 18:51:11 +0000163loop. Hint: the built-in function \function{range()} returns a
164sequence of integers suitable to emulate the effect of Pascal's
Fred Drake5c07d9b1998-05-14 19:37:06 +0000165\code{for i := a to b do};
Guido van Rossum5399d681998-07-24 18:51:11 +0000166e.g., \code{range(3)} returns the list \code{[0, 1, 2]}.
Fred Drakef6669171998-05-06 19:52:49 +0000167\bifuncindex{range}
Fred Drake5c07d9b1998-05-14 19:37:06 +0000168\indexii{Pascal}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000169
Fred Drake0aa811c2001-10-20 04:24:09 +0000170\warning{There is a subtlety when the sequence is being modified
Fred Drakef6669171998-05-06 19:52:49 +0000171by the loop (this can only occur for mutable sequences, i.e. lists).
172An internal counter is used to keep track of which item is used next,
173and this is incremented on each iteration. When this counter has
174reached the length of the sequence the loop terminates. This means that
175if the suite deletes the current (or a previous) item from the
176sequence, the next item will be skipped (since it gets the index of
177the current item which has already been treated). Likewise, if the
178suite inserts an item in the sequence before the current item, the
179current item will be treated again the next time through the loop.
180This can lead to nasty bugs that can be avoided by making a temporary
Guido van Rossum5399d681998-07-24 18:51:11 +0000181copy using a slice of the whole sequence, e.g.,
Fred Drakef6669171998-05-06 19:52:49 +0000182\index{loop!over mutable sequence}
Fred Drake0aa811c2001-10-20 04:24:09 +0000183\index{mutable sequence!loop over}}
Fred Drakef6669171998-05-06 19:52:49 +0000184
185\begin{verbatim}
186for x in a[:]:
187 if x < 0: a.remove(x)
188\end{verbatim}
189
Fred Drake2829f1c2001-06-23 05:27:20 +0000190
Fred Drake61c77281998-07-28 19:34:22 +0000191\section{The \keyword{try} statement\label{try}}
Fred Drakef6669171998-05-06 19:52:49 +0000192\stindex{try}
193
Fred Drake5c07d9b1998-05-14 19:37:06 +0000194The \keyword{try} statement specifies exception handlers and/or cleanup
Fred Drakef6669171998-05-06 19:52:49 +0000195code for a group of statements:
196
Fred Drakecb4638a2001-07-06 22:49:53 +0000197\begin{productionlist}
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000198 \production{try_stmt} {try1_stmt | try2_stmt}
199 \production{try1_stmt}
Fred Drake53815882002-03-15 23:21:37 +0000200 {"try" ":" \token{suite}}
201 \productioncont{("except" [\token{expression}
202 ["," \token{target}]] ":" \token{suite})+}
203 \productioncont{["else" ":" \token{suite}]}
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000204 \productioncont{["finally" ":" \token{suite}]}
205 \production{try2_stmt}
206 {"try" ":" \token{suite}}
207 \productioncont{"finally" ":" \token{suite}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000208\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000209
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000210\versionchanged[In previous versions of Python,
211\keyword{try}...\keyword{except}...\keyword{finally} did not work.
212\keyword{try}...\keyword{except} had to be nested in
213\keyword{try}...\keyword{finally}]{2.5}
Fred Drakef6669171998-05-06 19:52:49 +0000214
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000215The \keyword{except} clause(s) specify one or more exception handlers.
216When no exception occurs in the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000217\keyword{try} clause, no exception handler is executed. When an
218exception occurs in the \keyword{try} suite, a search for an exception
Guido van Rossum5399d681998-07-24 18:51:11 +0000219handler is started. This search inspects the except clauses in turn until
220one is found that matches the exception. An expression-less except
Fred Drakef6669171998-05-06 19:52:49 +0000221clause, if present, must be last; it matches any exception. For an
Guido van Rossum5399d681998-07-24 18:51:11 +0000222except clause with an expression, that expression is evaluated, and the
Fred Drakef6669171998-05-06 19:52:49 +0000223clause matches the exception if the resulting object is ``compatible''
224with the exception. An object is compatible with an exception if it
Michael W. Hudsona2a98882005-03-04 14:33:32 +0000225is the class or a base class of the exception object, a tuple
226containing an item compatible with the exception, or, in the
227(deprecated) case of string exceptions, is the raised string itself
228(note that the object identities must match, i.e. it must be the same
229string object, not just a string with the same value).
Fred Drakef6669171998-05-06 19:52:49 +0000230\kwindex{except}
231
232If no except clause matches the exception, the search for an exception
233handler continues in the surrounding code and on the invocation stack.
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000234\footnote{The exception is propogated to the invocation stack only if
235there is no \keyword{finally} clause that negates the exception.}
Fred Drakef6669171998-05-06 19:52:49 +0000236
Guido van Rossum5399d681998-07-24 18:51:11 +0000237If the evaluation of an expression in the header of an except clause
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000238raises an exception, the original search for a handler is canceled
Fred Drakef6669171998-05-06 19:52:49 +0000239and a search starts for the new exception in the surrounding code and
Fred Drake5c07d9b1998-05-14 19:37:06 +0000240on the call stack (it is treated as if the entire \keyword{try} statement
Fred Drakef6669171998-05-06 19:52:49 +0000241raised the exception).
242
Michael W. Hudsona2a98882005-03-04 14:33:32 +0000243When a matching except clause is found, the exception is assigned to
244the target specified in that except clause, if present, and the except
245clause's suite is executed. All except clauses must have an
246executable block. When the end of this block is reached, execution
247continues normally after the entire try statement. (This means that
248if two nested handlers exist for the same exception, and the exception
249occurs in the try clause of the inner handler, the outer handler will
250not handle the exception.)
Fred Drakef6669171998-05-06 19:52:49 +0000251
252Before an except clause's suite is executed, details about the
Fred Drake99cd5731999-02-12 20:40:09 +0000253exception are assigned to three variables in the
254\module{sys}\refbimodindex{sys} module: \code{sys.exc_type} receives
255the object identifying the exception; \code{sys.exc_value} receives
256the exception's parameter; \code{sys.exc_traceback} receives a
Fred Drake78eb2002002-10-18 15:20:32 +0000257traceback object\obindex{traceback} (see section~\ref{traceback})
Fred Drake99cd5731999-02-12 20:40:09 +0000258identifying the point in the program where the exception occurred.
Guido van Rossum5399d681998-07-24 18:51:11 +0000259These details are also available through the \function{sys.exc_info()}
Fred Drake99cd5731999-02-12 20:40:09 +0000260function, which returns a tuple \code{(\var{exc_type}, \var{exc_value},
261\var{exc_traceback})}. Use of the corresponding variables is
Guido van Rossum5399d681998-07-24 18:51:11 +0000262deprecated in favor of this function, since their use is unsafe in a
263threaded program. As of Python 1.5, the variables are restored to
264their previous values (before the call) when returning from a function
265that handled an exception.
Fred Drake99cd5731999-02-12 20:40:09 +0000266\withsubitem{(in module sys)}{\ttindex{exc_type}
267 \ttindex{exc_value}\ttindex{exc_traceback}}
Fred Drakef6669171998-05-06 19:52:49 +0000268
Fred Drake2cba0f62001-01-02 19:22:48 +0000269The optional \keyword{else} clause is executed if and when control
270flows off the end of the \keyword{try} clause.\footnote{
271 Currently, control ``flows off the end'' except in the case of an
272 exception or the execution of a \keyword{return},
273 \keyword{continue}, or \keyword{break} statement.
274} Exceptions in the \keyword{else} clause are not handled by the
275preceding \keyword{except} clauses.
Fred Drakef6669171998-05-06 19:52:49 +0000276\kwindex{else}
Fred Drake2cba0f62001-01-02 19:22:48 +0000277\stindex{return}
278\stindex{break}
279\stindex{continue}
Fred Drakef6669171998-05-06 19:52:49 +0000280
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000281If \keyword{finally} is present, it specifies a `cleanup' handler. The
282\keyword{try} clause is executed, including any \keyword{except} and
283\keyword{else} clauses. If an exception occurs in any of the clauses
284and is not handled, the exception is temporarily saved. The
285\keyword{finally} clause is executed. If there is a saved exception,
286it is re-raised at the end of the \keyword{finally} clause.
287If the \keyword{finally} clause raises another exception or
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000288executes a \keyword{return} or \keyword{break} statement, the saved
289exception is lost. A \keyword{continue} statement is illegal in the
290\keyword{finally} clause. (The reason is a problem with the current
Fred Drake216cbca2002-02-22 15:40:23 +0000291implementation -- this restriction may be lifted in the future). The
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000292exception information is not available to the program during execution of
293the \keyword{finally} clause.
Fred Drakef6669171998-05-06 19:52:49 +0000294\kwindex{finally}
295
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000296When a \keyword{return}, \keyword{break} or \keyword{continue} statement is
297executed in the \keyword{try} suite of a \keyword{try}...\keyword{finally}
298statement, the \keyword{finally} clause is also executed `on the way out.' A
299\keyword{continue} statement is illegal in the \keyword{finally} clause.
300(The reason is a problem with the current implementation --- this
Fred Drakef6669171998-05-06 19:52:49 +0000301restriction may be lifted in the future).
302\stindex{return}
303\stindex{break}
304\stindex{continue}
305
Fred Drake78eb2002002-10-18 15:20:32 +0000306Additional information on exceptions can be found in
307section~\ref{exceptions}, and information on using the \keyword{raise}
308statement to generate exceptions may be found in section~\ref{raise}.
309
Fred Drake2829f1c2001-06-23 05:27:20 +0000310
Fred Drake61c77281998-07-28 19:34:22 +0000311\section{Function definitions\label{function}}
Fred Drakef6669171998-05-06 19:52:49 +0000312\indexii{function}{definition}
Fred Drake687bde92001-12-27 18:38:10 +0000313\stindex{def}
Fred Drakef6669171998-05-06 19:52:49 +0000314
315A function definition defines a user-defined function object (see
Fred Drake78eb2002002-10-18 15:20:32 +0000316section~\ref{types}):
Fred Drakef6669171998-05-06 19:52:49 +0000317\obindex{user-defined function}
318\obindex{function}
319
Fred Drakecb4638a2001-07-06 22:49:53 +0000320\begin{productionlist}
321 \production{funcdef}
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000322 {[\token{decorators}] "def" \token{funcname} "(" [\token{parameter_list}] ")"
Fred Drakecb4638a2001-07-06 22:49:53 +0000323 ":" \token{suite}}
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000324 \production{decorators}
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000325 {\token{decorator}+}
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000326 \production{decorator}
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000327 {"@" \token{dotted_name} ["(" [\token{argument_list} [","]] ")"] NEWLINE}
Michael W. Hudson2f475a72005-05-26 07:58:22 +0000328 \production{dotted_name}
329 {\token{identifier} ("." \token{identifier})*}
Fred Drakecb4638a2001-07-06 22:49:53 +0000330 \production{parameter_list}
Fred Drake9a408512004-11-02 18:57:33 +0000331 {(\token{defparameter} ",")*}
332 \productioncont{(~~"*" \token{identifier} [, "**" \token{identifier}]}
333 \productioncont{ | "**" \token{identifier}}
334 \productioncont{ | \token{defparameter} [","] )}
Fred Drakecb4638a2001-07-06 22:49:53 +0000335 \production{defparameter}
336 {\token{parameter} ["=" \token{expression}]}
337 \production{sublist}
338 {\token{parameter} ("," \token{parameter})* [","]}
339 \production{parameter}
340 {\token{identifier} | "(" \token{sublist} ")"}
341 \production{funcname}
342 {\token{identifier}}
343\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000344
345A function definition is an executable statement. Its execution binds
Guido van Rossum5399d681998-07-24 18:51:11 +0000346the function name in the current local namespace to a function object
Fred Drakef6669171998-05-06 19:52:49 +0000347(a wrapper around the executable code for the function). This
Guido van Rossum5399d681998-07-24 18:51:11 +0000348function object contains a reference to the current global namespace
349as the global namespace to be used when the function is called.
Fred Drakef6669171998-05-06 19:52:49 +0000350\indexii{function}{name}
351\indexii{name}{binding}
352
353The function definition does not execute the function body; this gets
354executed only when the function is called.
355
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000356A function definition may be wrapped by one or more decorator expressions.
357Decorator expressions are evaluated when the function is defined, in the scope
358that contains the function definition. The result must be a callable,
359which is invoked with the function object as the only argument.
360The returned value is bound to the function name instead of the function
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000361object. Multiple decorators are applied in nested fashion.
362For example, the following code:
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000363
364\begin{verbatim}
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000365@f1(arg)
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000366@f2
367def func(): pass
368\end{verbatim}
369
370is equivalent to:
371
372\begin{verbatim}
373def func(): pass
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000374func = f1(arg)(f2(func))
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000375\end{verbatim}
376
Guido van Rossum5399d681998-07-24 18:51:11 +0000377When one or more top-level parameters have the form \var{parameter}
378\code{=} \var{expression}, the function is said to have ``default
Guido van Rossume0394391998-12-04 19:37:10 +0000379parameter values.'' For a parameter with a
Guido van Rossum5399d681998-07-24 18:51:11 +0000380default value, the corresponding argument may be omitted from a call,
381in which case the parameter's default value is substituted. If a
382parameter has a default value, all following parameters must also have
383a default value --- this is a syntactic restriction that is not
Fred Drakee15956b2000-04-03 04:51:13 +0000384expressed by the grammar.
Fred Drakef6669171998-05-06 19:52:49 +0000385\indexiii{default}{parameter}{value}
386
Guido van Rossume0394391998-12-04 19:37:10 +0000387\strong{Default parameter values are evaluated when the function
388definition is executed.} This means that the expression is evaluated
389once, when the function is defined, and that that same
390``pre-computed'' value is used for each call. This is especially
391important to understand when a default parameter is a mutable object,
392such as a list or a dictionary: if the function modifies the object
393(e.g. by appending an item to a list), the default value is in effect
394modified. This is generally not what was intended. A way around this
395is to use \code{None} as the default, and explicitly test for it in
396the body of the function, e.g.:
397
398\begin{verbatim}
399def whats_on_the_telly(penguin=None):
400 if penguin is None:
401 penguin = []
402 penguin.append("property of the zoo")
403 return penguin
404\end{verbatim}
405
Fred Drake78eb2002002-10-18 15:20:32 +0000406Function call semantics are described in more detail in
407section~\ref{calls}.
Guido van Rossum5399d681998-07-24 18:51:11 +0000408A function call always assigns values to all parameters mentioned in
409the parameter list, either from position arguments, from keyword
410arguments, or from default values. If the form ``\code{*identifier}''
411is present, it is initialized to a tuple receiving any excess
412positional parameters, defaulting to the empty tuple. If the form
413``\code{**identifier}'' is present, it is initialized to a new
414dictionary receiving any excess keyword arguments, defaulting to a
415new empty dictionary.
Fred Drakef6669171998-05-06 19:52:49 +0000416
Fred Drakef6669171998-05-06 19:52:49 +0000417It is also possible to create anonymous functions (functions not bound
418to a name), for immediate use in expressions. This uses lambda forms,
Fred Drake78eb2002002-10-18 15:20:32 +0000419described in section~\ref{lambda}. Note that the lambda form is
Guido van Rossum5399d681998-07-24 18:51:11 +0000420merely a shorthand for a simplified function definition; a function
421defined in a ``\keyword{def}'' statement can be passed around or
422assigned to another name just like a function defined by a lambda
423form. The ``\keyword{def}'' form is actually more powerful since it
424allows the execution of multiple statements.
Fred Drakef6669171998-05-06 19:52:49 +0000425\indexii{lambda}{form}
426
Jeremy Hylton1824b592002-04-01 21:30:15 +0000427\strong{Programmer's note:} Functions are first-class objects. A
428``\code{def}'' form executed inside a function definition defines a
429local function that can be returned or passed around. Free variables
430used in the nested function can access the local variables of the
Fred Drake78eb2002002-10-18 15:20:32 +0000431function containing the def. See section~\ref{naming} for details.
Guido van Rossum5399d681998-07-24 18:51:11 +0000432
Fred Drake2829f1c2001-06-23 05:27:20 +0000433
Fred Drake61c77281998-07-28 19:34:22 +0000434\section{Class definitions\label{class}}
Fred Drakef6669171998-05-06 19:52:49 +0000435\indexii{class}{definition}
Fred Drake687bde92001-12-27 18:38:10 +0000436\stindex{class}
Fred Drakef6669171998-05-06 19:52:49 +0000437
Fred Drake78eb2002002-10-18 15:20:32 +0000438A class definition defines a class object (see section~\ref{types}):
Fred Drakef6669171998-05-06 19:52:49 +0000439\obindex{class}
440
Fred Drakecb4638a2001-07-06 22:49:53 +0000441\begin{productionlist}
442 \production{classdef}
443 {"class" \token{classname} [\token{inheritance}] ":"
444 \token{suite}}
445 \production{inheritance}
Brett Cannon629496b2005-04-09 03:03:00 +0000446 {"(" [\token{expression_list}] ")"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000447 \production{classname}
448 {\token{identifier}}
449\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000450
451A class definition is an executable statement. It first evaluates the
452inheritance list, if present. Each item in the inheritance list
Fred Drake2348afd2003-09-24 04:11:47 +0000453should evaluate to a class object or class type which allows
454subclassing. The class's suite is then executed
Fred Drake78eb2002002-10-18 15:20:32 +0000455in a new execution frame (see section~\ref{naming}), using a newly
Guido van Rossum5399d681998-07-24 18:51:11 +0000456created local namespace and the original global namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000457(Usually, the suite contains only function definitions.) When the
458class's suite finishes execution, its execution frame is discarded but
Guido van Rossum5399d681998-07-24 18:51:11 +0000459its local namespace is saved. A class object is then created using
460the inheritance list for the base classes and the saved local
461namespace for the attribute dictionary. The class name is bound to this
462class object in the original local namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000463\index{inheritance}
464\indexii{class}{name}
465\indexii{name}{binding}
466\indexii{execution}{frame}
Guido van Rossum5399d681998-07-24 18:51:11 +0000467
Fred Drake2348afd2003-09-24 04:11:47 +0000468\strong{Programmer's note:} Variables defined in the class definition
Guido van Rossum5399d681998-07-24 18:51:11 +0000469are class variables; they are shared by all instances. To define
Raymond Hettingerc7a26562003-08-12 00:01:17 +0000470instance variables, they must be given a value in the
Guido van Rossum5399d681998-07-24 18:51:11 +0000471\method{__init__()} method or in another method. Both class and
472instance variables are accessible through the notation
Fred Drake7c116d72001-05-10 15:09:36 +0000473``\code{self.name}'', and an instance variable hides a class variable
Guido van Rossum5399d681998-07-24 18:51:11 +0000474with the same name when accessed in this way. Class variables with
475immutable values can be used as defaults for instance variables.
Fred Drake2348afd2003-09-24 04:11:47 +0000476For new-style classes, descriptors can be used to create instance
477variables with different implementation details.