blob: a2d46a8d703ccc4e29b9548e4eeeca719f18a959 [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}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000049 \productioncont{| \token{with_stmt}}
Fred Drake53815882002-03-15 23:21:37 +000050 \productioncont{| \token{funcdef}}
51 \productioncont{| \token{classdef}}
Fred Drakecb4638a2001-07-06 22:49:53 +000052 \production{suite}
53 {\token{stmt_list} NEWLINE
54 | NEWLINE INDENT \token{statement}+ DEDENT}
55 \production{statement}
56 {\token{stmt_list} NEWLINE | \token{compound_stmt}}
57 \production{stmt_list}
58 {\token{simple_stmt} (";" \token{simple_stmt})* [";"]}
59\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000060
Guido van Rossum5399d681998-07-24 18:51:11 +000061Note that statements always end in a
62\code{NEWLINE}\index{NEWLINE token} possibly followed by a
63\code{DEDENT}.\index{DEDENT token} Also note that optional
64continuation clauses always begin with a keyword that cannot start a
65statement, thus there are no ambiguities (the `dangling
66\keyword{else}' problem is solved in Python by requiring nested
67\keyword{if} statements to be indented).
Fred Drakef6669171998-05-06 19:52:49 +000068\indexii{dangling}{else}
69
70The formatting of the grammar rules in the following sections places
71each clause on a separate line for clarity.
72
Fred Drake2829f1c2001-06-23 05:27:20 +000073
Fred Drake61c77281998-07-28 19:34:22 +000074\section{The \keyword{if} statement\label{if}}
Fred Drakef6669171998-05-06 19:52:49 +000075\stindex{if}
76
Fred Drake5c07d9b1998-05-14 19:37:06 +000077The \keyword{if} statement is used for conditional execution:
Fred Drakef6669171998-05-06 19:52:49 +000078
Fred Drakecb4638a2001-07-06 22:49:53 +000079\begin{productionlist}
80 \production{if_stmt}
Fred Drake53815882002-03-15 23:21:37 +000081 {"if" \token{expression} ":" \token{suite}}
82 \productioncont{( "elif" \token{expression} ":" \token{suite} )*}
83 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +000084\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000085
Guido van Rossum5399d681998-07-24 18:51:11 +000086It selects exactly one of the suites by evaluating the expressions one
Fred Drake78eb2002002-10-18 15:20:32 +000087by one until one is found to be true (see section~\ref{Booleans} for
Fred Drakef6669171998-05-06 19:52:49 +000088the definition of true and false); then that suite is executed (and no
Fred Drake5c07d9b1998-05-14 19:37:06 +000089other part of the \keyword{if} statement is executed or evaluated). If
Guido van Rossum5399d681998-07-24 18:51:11 +000090all expressions are false, the suite of the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +000091present, is executed.
92\kwindex{elif}
93\kwindex{else}
94
Fred Drake2829f1c2001-06-23 05:27:20 +000095
Fred Drake61c77281998-07-28 19:34:22 +000096\section{The \keyword{while} statement\label{while}}
Fred Drakef6669171998-05-06 19:52:49 +000097\stindex{while}
98\indexii{loop}{statement}
99
Guido van Rossum5399d681998-07-24 18:51:11 +0000100The \keyword{while} statement is used for repeated execution as long
101as an expression is true:
Fred Drakef6669171998-05-06 19:52:49 +0000102
Fred Drakecb4638a2001-07-06 22:49:53 +0000103\begin{productionlist}
104 \production{while_stmt}
Fred Drake53815882002-03-15 23:21:37 +0000105 {"while" \token{expression} ":" \token{suite}}
106 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000107\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000108
Guido van Rossum5399d681998-07-24 18:51:11 +0000109This repeatedly tests the expression and, if it is true, executes the
110first suite; if the expression is false (which may be the first time it
Fred Drake5c07d9b1998-05-14 19:37:06 +0000111is tested) the suite of the \keyword{else} clause, if present, is
Fred Drakef6669171998-05-06 19:52:49 +0000112executed and the loop terminates.
113\kwindex{else}
114
Fred Drake5c07d9b1998-05-14 19:37:06 +0000115A \keyword{break} statement executed in the first suite terminates the
116loop without executing the \keyword{else} clause's suite. A
117\keyword{continue} statement executed in the first suite skips the rest
Guido van Rossum5399d681998-07-24 18:51:11 +0000118of the suite and goes back to testing the expression.
Fred Drakef6669171998-05-06 19:52:49 +0000119\stindex{break}
120\stindex{continue}
121
Fred Drake2829f1c2001-06-23 05:27:20 +0000122
Fred Drake61c77281998-07-28 19:34:22 +0000123\section{The \keyword{for} statement\label{for}}
Fred Drakef6669171998-05-06 19:52:49 +0000124\stindex{for}
125\indexii{loop}{statement}
126
Fred Drake5c07d9b1998-05-14 19:37:06 +0000127The \keyword{for} statement is used to iterate over the elements of a
Fred Drake93852ef2001-06-23 06:06:52 +0000128sequence (such as a string, tuple or list) or other iterable object:
Fred Drakef6669171998-05-06 19:52:49 +0000129\obindex{sequence}
130
Fred Drakecb4638a2001-07-06 22:49:53 +0000131\begin{productionlist}
132 \production{for_stmt}
133 {"for" \token{target_list} "in" \token{expression_list}
Fred Drake53815882002-03-15 23:21:37 +0000134 ":" \token{suite}}
135 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000136\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000137
Fred Drake7fabaf82004-11-02 19:18:20 +0000138The expression list is evaluated once; it should yield an iterable
139object. An iterator is created for the result of the
140{}\code{expression_list}. The suite is then executed once for each
141item provided by the iterator, in the
Fred Drakef6669171998-05-06 19:52:49 +0000142order of ascending indices. Each item in turn is assigned to the
143target list using the standard rules for assignments, and then the
144suite is executed. When the items are exhausted (which is immediately
Fred Drake5c07d9b1998-05-14 19:37:06 +0000145when the sequence is empty), the suite in the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +0000146present, is executed, and the loop terminates.
147\kwindex{in}
148\kwindex{else}
149\indexii{target}{list}
150
Fred Drake5c07d9b1998-05-14 19:37:06 +0000151A \keyword{break} statement executed in the first suite terminates the
152loop without executing the \keyword{else} clause's suite. A
153\keyword{continue} statement executed in the first suite skips the rest
154of the suite and continues with the next item, or with the \keyword{else}
Fred Drakef6669171998-05-06 19:52:49 +0000155clause if there was no next item.
156\stindex{break}
157\stindex{continue}
158
159The suite may assign to the variable(s) in the target list; this does
160not affect the next item assigned to it.
161
162The target list is not deleted when the loop is finished, but if the
163sequence is empty, it will not have been assigned to at all by the
Guido van Rossum5399d681998-07-24 18:51:11 +0000164loop. Hint: the built-in function \function{range()} returns a
165sequence of integers suitable to emulate the effect of Pascal's
Fred Drake5c07d9b1998-05-14 19:37:06 +0000166\code{for i := a to b do};
Guido van Rossum5399d681998-07-24 18:51:11 +0000167e.g., \code{range(3)} returns the list \code{[0, 1, 2]}.
Fred Drakef6669171998-05-06 19:52:49 +0000168\bifuncindex{range}
Fred Drake5c07d9b1998-05-14 19:37:06 +0000169\indexii{Pascal}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000170
Fred Drake0aa811c2001-10-20 04:24:09 +0000171\warning{There is a subtlety when the sequence is being modified
Fred Drakef6669171998-05-06 19:52:49 +0000172by the loop (this can only occur for mutable sequences, i.e. lists).
173An internal counter is used to keep track of which item is used next,
174and this is incremented on each iteration. When this counter has
175reached the length of the sequence the loop terminates. This means that
176if the suite deletes the current (or a previous) item from the
177sequence, the next item will be skipped (since it gets the index of
178the current item which has already been treated). Likewise, if the
179suite inserts an item in the sequence before the current item, the
180current item will be treated again the next time through the loop.
181This can lead to nasty bugs that can be avoided by making a temporary
Guido van Rossum5399d681998-07-24 18:51:11 +0000182copy using a slice of the whole sequence, e.g.,
Fred Drakef6669171998-05-06 19:52:49 +0000183\index{loop!over mutable sequence}
Fred Drake0aa811c2001-10-20 04:24:09 +0000184\index{mutable sequence!loop over}}
Fred Drakef6669171998-05-06 19:52:49 +0000185
186\begin{verbatim}
187for x in a[:]:
188 if x < 0: a.remove(x)
189\end{verbatim}
190
Fred Drake2829f1c2001-06-23 05:27:20 +0000191
Fred Drake61c77281998-07-28 19:34:22 +0000192\section{The \keyword{try} statement\label{try}}
Fred Drakef6669171998-05-06 19:52:49 +0000193\stindex{try}
194
Fred Drake5c07d9b1998-05-14 19:37:06 +0000195The \keyword{try} statement specifies exception handlers and/or cleanup
Fred Drakef6669171998-05-06 19:52:49 +0000196code for a group of statements:
197
Fred Drakecb4638a2001-07-06 22:49:53 +0000198\begin{productionlist}
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000199 \production{try_stmt} {try1_stmt | try2_stmt}
200 \production{try1_stmt}
Fred Drake53815882002-03-15 23:21:37 +0000201 {"try" ":" \token{suite}}
202 \productioncont{("except" [\token{expression}
203 ["," \token{target}]] ":" \token{suite})+}
204 \productioncont{["else" ":" \token{suite}]}
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000205 \productioncont{["finally" ":" \token{suite}]}
206 \production{try2_stmt}
207 {"try" ":" \token{suite}}
208 \productioncont{"finally" ":" \token{suite}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000209\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000210
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000211\versionchanged[In previous versions of Python,
212\keyword{try}...\keyword{except}...\keyword{finally} did not work.
213\keyword{try}...\keyword{except} had to be nested in
214\keyword{try}...\keyword{finally}]{2.5}
Fred Drakef6669171998-05-06 19:52:49 +0000215
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000216The \keyword{except} clause(s) specify one or more exception handlers.
217When no exception occurs in the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000218\keyword{try} clause, no exception handler is executed. When an
219exception occurs in the \keyword{try} suite, a search for an exception
Guido van Rossum5399d681998-07-24 18:51:11 +0000220handler is started. This search inspects the except clauses in turn until
221one is found that matches the exception. An expression-less except
Fred Drakef6669171998-05-06 19:52:49 +0000222clause, if present, must be last; it matches any exception. For an
Guido van Rossum5399d681998-07-24 18:51:11 +0000223except clause with an expression, that expression is evaluated, and the
Fred Drakef6669171998-05-06 19:52:49 +0000224clause matches the exception if the resulting object is ``compatible''
225with the exception. An object is compatible with an exception if it
Michael W. Hudsona2a98882005-03-04 14:33:32 +0000226is the class or a base class of the exception object, a tuple
227containing an item compatible with the exception, or, in the
228(deprecated) case of string exceptions, is the raised string itself
229(note that the object identities must match, i.e. it must be the same
230string object, not just a string with the same value).
Fred Drakef6669171998-05-06 19:52:49 +0000231\kwindex{except}
232
233If no except clause matches the exception, the search for an exception
234handler continues in the surrounding code and on the invocation stack.
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000235\footnote{The exception is propogated to the invocation stack only if
236there is no \keyword{finally} clause that negates the exception.}
Fred Drakef6669171998-05-06 19:52:49 +0000237
Guido van Rossum5399d681998-07-24 18:51:11 +0000238If the evaluation of an expression in the header of an except clause
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000239raises an exception, the original search for a handler is canceled
Fred Drakef6669171998-05-06 19:52:49 +0000240and a search starts for the new exception in the surrounding code and
Fred Drake5c07d9b1998-05-14 19:37:06 +0000241on the call stack (it is treated as if the entire \keyword{try} statement
Fred Drakef6669171998-05-06 19:52:49 +0000242raised the exception).
243
Michael W. Hudsona2a98882005-03-04 14:33:32 +0000244When a matching except clause is found, the exception is assigned to
245the target specified in that except clause, if present, and the except
246clause's suite is executed. All except clauses must have an
247executable block. When the end of this block is reached, execution
248continues normally after the entire try statement. (This means that
249if two nested handlers exist for the same exception, and the exception
250occurs in the try clause of the inner handler, the outer handler will
251not handle the exception.)
Fred Drakef6669171998-05-06 19:52:49 +0000252
253Before an except clause's suite is executed, details about the
Neal Norwitzac3625f2006-03-17 05:49:33 +0000254exception are stored in the \module{sys}\refbimodindex{sys} module
255and can be access via \function{sys.exc_info()}. \function{sys.exc_info()}
256returns a 3-tuple consisting of: \code{exc_type} receives
257the object identifying the exception; \code{exc_value} receives
258the exception's parameter; \code{exc_traceback} receives a
Fred Drake78eb2002002-10-18 15:20:32 +0000259traceback object\obindex{traceback} (see section~\ref{traceback})
Fred Drake99cd5731999-02-12 20:40:09 +0000260identifying the point in the program where the exception occurred.
Neal Norwitzac3625f2006-03-17 05:49:33 +0000261\function{sys.exc_info()} values are restored to their previous values
262(before the call) when returning from a function that handled an exception.
Fred Drakef6669171998-05-06 19:52:49 +0000263
Fred Drake2cba0f62001-01-02 19:22:48 +0000264The optional \keyword{else} clause is executed if and when control
265flows off the end of the \keyword{try} clause.\footnote{
266 Currently, control ``flows off the end'' except in the case of an
267 exception or the execution of a \keyword{return},
268 \keyword{continue}, or \keyword{break} statement.
269} Exceptions in the \keyword{else} clause are not handled by the
270preceding \keyword{except} clauses.
Fred Drakef6669171998-05-06 19:52:49 +0000271\kwindex{else}
Fred Drake2cba0f62001-01-02 19:22:48 +0000272\stindex{return}
273\stindex{break}
274\stindex{continue}
Fred Drakef6669171998-05-06 19:52:49 +0000275
Neal Norwitz11ca77e2005-12-17 22:24:12 +0000276If \keyword{finally} is present, it specifies a `cleanup' handler. The
277\keyword{try} clause is executed, including any \keyword{except} and
278\keyword{else} clauses. If an exception occurs in any of the clauses
279and is not handled, the exception is temporarily saved. The
280\keyword{finally} clause is executed. If there is a saved exception,
281it is re-raised at the end of the \keyword{finally} clause.
282If the \keyword{finally} clause raises another exception or
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000283executes a \keyword{return} or \keyword{break} statement, the saved
284exception is lost. A \keyword{continue} statement is illegal in the
285\keyword{finally} clause. (The reason is a problem with the current
Fred Drake216cbca2002-02-22 15:40:23 +0000286implementation -- this restriction may be lifted in the future). The
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000287exception information is not available to the program during execution of
288the \keyword{finally} clause.
Fred Drakef6669171998-05-06 19:52:49 +0000289\kwindex{finally}
290
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000291When a \keyword{return}, \keyword{break} or \keyword{continue} statement is
292executed in the \keyword{try} suite of a \keyword{try}...\keyword{finally}
293statement, the \keyword{finally} clause is also executed `on the way out.' A
294\keyword{continue} statement is illegal in the \keyword{finally} clause.
295(The reason is a problem with the current implementation --- this
Fred Drakef6669171998-05-06 19:52:49 +0000296restriction may be lifted in the future).
297\stindex{return}
298\stindex{break}
299\stindex{continue}
300
Fred Drake78eb2002002-10-18 15:20:32 +0000301Additional information on exceptions can be found in
302section~\ref{exceptions}, and information on using the \keyword{raise}
303statement to generate exceptions may be found in section~\ref{raise}.
304
Fred Drake2829f1c2001-06-23 05:27:20 +0000305
Guido van Rossumc2e20742006-02-27 22:32:47 +0000306\section{The \keyword{with} statement\label{with}}
307\stindex{with}
308
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000309\versionadded{2.5}
Guido van Rossumc2e20742006-02-27 22:32:47 +0000310
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311The \keyword{with} statement is used to wrap the execution of a block
312with methods defined by a context manager (see
313section~\ref{context-managers}). This allows common
314\keyword{try}...\keyword{except}...\keyword{finally} usage patterns to
315be encapsulated as context managers for convenient reuse.
316
317\begin{productionlist}
318 \production{with_stmt}
319 {"with" \token{expression} ["as" target_list] ":" \token{suite}}
320\end{productionlist}
321
322The execution of the \keyword{with} statement proceeds as follows:
323
324\begin{enumerate}
325
326\item The expression is evaluated, to obtain a context manager
327object.
328
329\item The context manager's \method{__context__()} method is invoked to
330obtain a context object.
331
332\item The context object's \method{__enter__()} method is invoked.
333
334\item If a target list was included in the \keyword{with}
335statement, the return value from \method{__enter__()} is assigned to it.
336
337\note{The \keyword{with} statement guarantees that if the
338\method{__enter__()} method returns without an error, then
339\method{__exit__()} will always be called. Thus, if an error occurs
340during the assignment to the target list, it will be treated the same as
341an error occurring within the suite would be. See step 6 below.}
342
343\item The suite is executed.
344
345\item The context object's \method{__exit__()} method is invoked. If an
346exception caused the suite to be exited, its type, value, and
347traceback are passed as arguments to \method{__exit__()}. Otherwise,
348three \constant{None} arguments are supplied.
349
350If the suite was exited due to an exception, and the return
351value from the \method{__exit__()} method was false, the exception is
352reraised. If the return value was true, the exception is suppressed, and
353execution continues with the statement following the \keyword{with}
354statement.
355
356If the suite was exited for any reason other than an exception, the
357return value from \method{__exit__()} is ignored, and execution proceeds
358at the normal location for the kind of exit that was taken.
359
360\end{enumerate}
361
362\begin{notice}
363In Python 2.5, the \keyword{with} statement is only allowed
364when the \code{with_statement} feature has been enabled. It will always
365be enabled in Python 2.6. This \code{__future__} import statement can
366be used to enable the feature:
367
368\begin{verbatim}
369from __future__ import with_statement
370\end{verbatim}
371\end{notice}
372
373\begin{seealso}
374 \seepep{0343}{The "with" statement}
375 {The specification, background, and examples for the
376 Python \keyword{with} statement.}
377\end{seealso}
Guido van Rossumc2e20742006-02-27 22:32:47 +0000378
Fred Drake61c77281998-07-28 19:34:22 +0000379\section{Function definitions\label{function}}
Fred Drakef6669171998-05-06 19:52:49 +0000380\indexii{function}{definition}
Fred Drake687bde92001-12-27 18:38:10 +0000381\stindex{def}
Fred Drakef6669171998-05-06 19:52:49 +0000382
383A function definition defines a user-defined function object (see
Fred Drake78eb2002002-10-18 15:20:32 +0000384section~\ref{types}):
Fred Drakef6669171998-05-06 19:52:49 +0000385\obindex{user-defined function}
386\obindex{function}
387
Fred Drakecb4638a2001-07-06 22:49:53 +0000388\begin{productionlist}
389 \production{funcdef}
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000390 {[\token{decorators}] "def" \token{funcname} "(" [\token{parameter_list}] ")"
Fred Drakecb4638a2001-07-06 22:49:53 +0000391 ":" \token{suite}}
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000392 \production{decorators}
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000393 {\token{decorator}+}
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000394 \production{decorator}
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000395 {"@" \token{dotted_name} ["(" [\token{argument_list} [","]] ")"] NEWLINE}
Michael W. Hudson2f475a72005-05-26 07:58:22 +0000396 \production{dotted_name}
397 {\token{identifier} ("." \token{identifier})*}
Fred Drakecb4638a2001-07-06 22:49:53 +0000398 \production{parameter_list}
Fred Drake9a408512004-11-02 18:57:33 +0000399 {(\token{defparameter} ",")*}
400 \productioncont{(~~"*" \token{identifier} [, "**" \token{identifier}]}
401 \productioncont{ | "**" \token{identifier}}
402 \productioncont{ | \token{defparameter} [","] )}
Fred Drakecb4638a2001-07-06 22:49:53 +0000403 \production{defparameter}
404 {\token{parameter} ["=" \token{expression}]}
405 \production{sublist}
406 {\token{parameter} ("," \token{parameter})* [","]}
407 \production{parameter}
408 {\token{identifier} | "(" \token{sublist} ")"}
409 \production{funcname}
410 {\token{identifier}}
411\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000412
413A function definition is an executable statement. Its execution binds
Guido van Rossum5399d681998-07-24 18:51:11 +0000414the function name in the current local namespace to a function object
Fred Drakef6669171998-05-06 19:52:49 +0000415(a wrapper around the executable code for the function). This
Guido van Rossum5399d681998-07-24 18:51:11 +0000416function object contains a reference to the current global namespace
417as the global namespace to be used when the function is called.
Fred Drakef6669171998-05-06 19:52:49 +0000418\indexii{function}{name}
419\indexii{name}{binding}
420
421The function definition does not execute the function body; this gets
422executed only when the function is called.
423
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000424A function definition may be wrapped by one or more decorator expressions.
425Decorator expressions are evaluated when the function is defined, in the scope
426that contains the function definition. The result must be a callable,
427which is invoked with the function object as the only argument.
428The returned value is bound to the function name instead of the function
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000429object. Multiple decorators are applied in nested fashion.
430For example, the following code:
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000431
432\begin{verbatim}
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000433@f1(arg)
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000434@f2
435def func(): pass
436\end{verbatim}
437
438is equivalent to:
439
440\begin{verbatim}
441def func(): pass
Michael W. Hudson0ccff072004-08-17 17:29:16 +0000442func = f1(arg)(f2(func))
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000443\end{verbatim}
444
Guido van Rossum5399d681998-07-24 18:51:11 +0000445When one or more top-level parameters have the form \var{parameter}
446\code{=} \var{expression}, the function is said to have ``default
Guido van Rossume0394391998-12-04 19:37:10 +0000447parameter values.'' For a parameter with a
Guido van Rossum5399d681998-07-24 18:51:11 +0000448default value, the corresponding argument may be omitted from a call,
449in which case the parameter's default value is substituted. If a
450parameter has a default value, all following parameters must also have
451a default value --- this is a syntactic restriction that is not
Fred Drakee15956b2000-04-03 04:51:13 +0000452expressed by the grammar.
Fred Drakef6669171998-05-06 19:52:49 +0000453\indexiii{default}{parameter}{value}
454
Guido van Rossume0394391998-12-04 19:37:10 +0000455\strong{Default parameter values are evaluated when the function
456definition is executed.} This means that the expression is evaluated
457once, when the function is defined, and that that same
458``pre-computed'' value is used for each call. This is especially
459important to understand when a default parameter is a mutable object,
460such as a list or a dictionary: if the function modifies the object
461(e.g. by appending an item to a list), the default value is in effect
462modified. This is generally not what was intended. A way around this
463is to use \code{None} as the default, and explicitly test for it in
464the body of the function, e.g.:
465
466\begin{verbatim}
467def whats_on_the_telly(penguin=None):
468 if penguin is None:
469 penguin = []
470 penguin.append("property of the zoo")
471 return penguin
472\end{verbatim}
473
Fred Drake78eb2002002-10-18 15:20:32 +0000474Function call semantics are described in more detail in
475section~\ref{calls}.
Guido van Rossum5399d681998-07-24 18:51:11 +0000476A function call always assigns values to all parameters mentioned in
477the parameter list, either from position arguments, from keyword
478arguments, or from default values. If the form ``\code{*identifier}''
479is present, it is initialized to a tuple receiving any excess
480positional parameters, defaulting to the empty tuple. If the form
481``\code{**identifier}'' is present, it is initialized to a new
482dictionary receiving any excess keyword arguments, defaulting to a
483new empty dictionary.
Fred Drakef6669171998-05-06 19:52:49 +0000484
Fred Drakef6669171998-05-06 19:52:49 +0000485It is also possible to create anonymous functions (functions not bound
486to a name), for immediate use in expressions. This uses lambda forms,
Fred Drake78eb2002002-10-18 15:20:32 +0000487described in section~\ref{lambda}. Note that the lambda form is
Guido van Rossum5399d681998-07-24 18:51:11 +0000488merely a shorthand for a simplified function definition; a function
489defined in a ``\keyword{def}'' statement can be passed around or
490assigned to another name just like a function defined by a lambda
491form. The ``\keyword{def}'' form is actually more powerful since it
492allows the execution of multiple statements.
Fred Drakef6669171998-05-06 19:52:49 +0000493\indexii{lambda}{form}
494
Jeremy Hylton1824b592002-04-01 21:30:15 +0000495\strong{Programmer's note:} Functions are first-class objects. A
496``\code{def}'' form executed inside a function definition defines a
497local function that can be returned or passed around. Free variables
498used in the nested function can access the local variables of the
Fred Drake78eb2002002-10-18 15:20:32 +0000499function containing the def. See section~\ref{naming} for details.
Guido van Rossum5399d681998-07-24 18:51:11 +0000500
Fred Drake2829f1c2001-06-23 05:27:20 +0000501
Fred Drake61c77281998-07-28 19:34:22 +0000502\section{Class definitions\label{class}}
Fred Drakef6669171998-05-06 19:52:49 +0000503\indexii{class}{definition}
Fred Drake687bde92001-12-27 18:38:10 +0000504\stindex{class}
Fred Drakef6669171998-05-06 19:52:49 +0000505
Fred Drake78eb2002002-10-18 15:20:32 +0000506A class definition defines a class object (see section~\ref{types}):
Fred Drakef6669171998-05-06 19:52:49 +0000507\obindex{class}
508
Fred Drakecb4638a2001-07-06 22:49:53 +0000509\begin{productionlist}
510 \production{classdef}
511 {"class" \token{classname} [\token{inheritance}] ":"
512 \token{suite}}
513 \production{inheritance}
Brett Cannon629496b2005-04-09 03:03:00 +0000514 {"(" [\token{expression_list}] ")"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000515 \production{classname}
516 {\token{identifier}}
517\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000518
519A class definition is an executable statement. It first evaluates the
520inheritance list, if present. Each item in the inheritance list
Fred Drake2348afd2003-09-24 04:11:47 +0000521should evaluate to a class object or class type which allows
522subclassing. The class's suite is then executed
Fred Drake78eb2002002-10-18 15:20:32 +0000523in a new execution frame (see section~\ref{naming}), using a newly
Guido van Rossum5399d681998-07-24 18:51:11 +0000524created local namespace and the original global namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000525(Usually, the suite contains only function definitions.) When the
526class's suite finishes execution, its execution frame is discarded but
Guido van Rossum5399d681998-07-24 18:51:11 +0000527its local namespace is saved. A class object is then created using
528the inheritance list for the base classes and the saved local
529namespace for the attribute dictionary. The class name is bound to this
530class object in the original local namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000531\index{inheritance}
532\indexii{class}{name}
533\indexii{name}{binding}
534\indexii{execution}{frame}
Guido van Rossum5399d681998-07-24 18:51:11 +0000535
Fred Drake2348afd2003-09-24 04:11:47 +0000536\strong{Programmer's note:} Variables defined in the class definition
Guido van Rossum5399d681998-07-24 18:51:11 +0000537are class variables; they are shared by all instances. To define
Raymond Hettingerc7a26562003-08-12 00:01:17 +0000538instance variables, they must be given a value in the
Guido van Rossum5399d681998-07-24 18:51:11 +0000539\method{__init__()} method or in another method. Both class and
540instance variables are accessible through the notation
Fred Drake7c116d72001-05-10 15:09:36 +0000541``\code{self.name}'', and an instance variable hides a class variable
Guido van Rossum5399d681998-07-24 18:51:11 +0000542with the same name when accessed in this way. Class variables with
543immutable values can be used as defaults for instance variables.
Fred Drake2348afd2003-09-24 04:11:47 +0000544For new-style classes, descriptors can be used to create instance
545variables with different implementation details.