blob: 265c0b8e6fdfe391dcb96c16cc0099d941c95213 [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 Drakef6669171998-05-06 19:52:49 +000086by one until one is found to be true (see section \ref{Booleans} for
87the 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
Guido van Rossum5399d681998-07-24 18:51:11 +0000137The expression list is evaluated once; it should yield a sequence. The
Fred Drakef6669171998-05-06 19:52:49 +0000138suite is then executed once for each item in the sequence, in the
139order of ascending indices. Each item in turn is assigned to the
140target list using the standard rules for assignments, and then the
141suite is executed. When the items are exhausted (which is immediately
Fred Drake5c07d9b1998-05-14 19:37:06 +0000142when the sequence is empty), the suite in the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +0000143present, is executed, and the loop terminates.
144\kwindex{in}
145\kwindex{else}
146\indexii{target}{list}
147
Fred Drake5c07d9b1998-05-14 19:37:06 +0000148A \keyword{break} statement executed in the first suite terminates the
149loop without executing the \keyword{else} clause's suite. A
150\keyword{continue} statement executed in the first suite skips the rest
151of the suite and continues with the next item, or with the \keyword{else}
Fred Drakef6669171998-05-06 19:52:49 +0000152clause if there was no next item.
153\stindex{break}
154\stindex{continue}
155
156The suite may assign to the variable(s) in the target list; this does
157not affect the next item assigned to it.
158
159The target list is not deleted when the loop is finished, but if the
160sequence is empty, it will not have been assigned to at all by the
Guido van Rossum5399d681998-07-24 18:51:11 +0000161loop. Hint: the built-in function \function{range()} returns a
162sequence of integers suitable to emulate the effect of Pascal's
Fred Drake5c07d9b1998-05-14 19:37:06 +0000163\code{for i := a to b do};
Guido van Rossum5399d681998-07-24 18:51:11 +0000164e.g., \code{range(3)} returns the list \code{[0, 1, 2]}.
Fred Drakef6669171998-05-06 19:52:49 +0000165\bifuncindex{range}
Fred Drake5c07d9b1998-05-14 19:37:06 +0000166\indexii{Pascal}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000167
Fred Drake0aa811c2001-10-20 04:24:09 +0000168\warning{There is a subtlety when the sequence is being modified
Fred Drakef6669171998-05-06 19:52:49 +0000169by the loop (this can only occur for mutable sequences, i.e. lists).
170An internal counter is used to keep track of which item is used next,
171and this is incremented on each iteration. When this counter has
172reached the length of the sequence the loop terminates. This means that
173if the suite deletes the current (or a previous) item from the
174sequence, the next item will be skipped (since it gets the index of
175the current item which has already been treated). Likewise, if the
176suite inserts an item in the sequence before the current item, the
177current item will be treated again the next time through the loop.
178This can lead to nasty bugs that can be avoided by making a temporary
Guido van Rossum5399d681998-07-24 18:51:11 +0000179copy using a slice of the whole sequence, e.g.,
Fred Drakef6669171998-05-06 19:52:49 +0000180\index{loop!over mutable sequence}
Fred Drake0aa811c2001-10-20 04:24:09 +0000181\index{mutable sequence!loop over}}
Fred Drakef6669171998-05-06 19:52:49 +0000182
183\begin{verbatim}
184for x in a[:]:
185 if x < 0: a.remove(x)
186\end{verbatim}
187
Fred Drake2829f1c2001-06-23 05:27:20 +0000188
Fred Drake61c77281998-07-28 19:34:22 +0000189\section{The \keyword{try} statement\label{try}}
Fred Drakef6669171998-05-06 19:52:49 +0000190\stindex{try}
191
Fred Drake5c07d9b1998-05-14 19:37:06 +0000192The \keyword{try} statement specifies exception handlers and/or cleanup
Fred Drakef6669171998-05-06 19:52:49 +0000193code for a group of statements:
194
Fred Drakecb4638a2001-07-06 22:49:53 +0000195\begin{productionlist}
196 \production{try_stmt}
197 {\token{try_exc_stmt} | \token{try_fin_stmt}}
198 \production{try_exc_stmt}
Fred Drake53815882002-03-15 23:21:37 +0000199 {"try" ":" \token{suite}}
200 \productioncont{("except" [\token{expression}
201 ["," \token{target}]] ":" \token{suite})+}
202 \productioncont{["else" ":" \token{suite}]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000203 \production{try_fin_stmt}
204 {"try" ":" \token{suite}
205 "finally" ":" \token{suite}}
206\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000207
Fred Drake5c07d9b1998-05-14 19:37:06 +0000208There are two forms of \keyword{try} statement:
209\keyword{try}...\keyword{except} and
Guido van Rossum5399d681998-07-24 18:51:11 +0000210\keyword{try}...\keyword{finally}. These forms cannot be mixed (but
211they can be nested in each other).
Fred Drakef6669171998-05-06 19:52:49 +0000212
Fred Drake5c07d9b1998-05-14 19:37:06 +0000213The \keyword{try}...\keyword{except} form specifies one or more
214exception handlers
215(the \keyword{except} clauses). When no exception occurs in the
216\keyword{try} clause, no exception handler is executed. When an
217exception occurs in the \keyword{try} suite, a search for an exception
Guido van Rossum5399d681998-07-24 18:51:11 +0000218handler is started. This search inspects the except clauses in turn until
219one is found that matches the exception. An expression-less except
Fred Drakef6669171998-05-06 19:52:49 +0000220clause, if present, must be last; it matches any exception. For an
Guido van Rossum5399d681998-07-24 18:51:11 +0000221except clause with an expression, that expression is evaluated, and the
Fred Drakef6669171998-05-06 19:52:49 +0000222clause matches the exception if the resulting object is ``compatible''
223with the exception. An object is compatible with an exception if it
224is either the object that identifies the exception, or (for exceptions
225that are classes) it is a base class of the exception, or it is a
226tuple containing an item that is compatible with the exception. Note
227that the object identities must match, i.e. it must be the same
228object, not just an object with the same value.
229\kwindex{except}
230
231If no except clause matches the exception, the search for an exception
232handler continues in the surrounding code and on the invocation stack.
233
Guido van Rossum5399d681998-07-24 18:51:11 +0000234If the evaluation of an expression in the header of an except clause
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000235raises an exception, the original search for a handler is canceled
Fred Drakef6669171998-05-06 19:52:49 +0000236and a search starts for the new exception in the surrounding code and
Fred Drake5c07d9b1998-05-14 19:37:06 +0000237on the call stack (it is treated as if the entire \keyword{try} statement
Fred Drakef6669171998-05-06 19:52:49 +0000238raised the exception).
239
240When a matching except clause is found, the exception's parameter is
241assigned to the target specified in that except clause, if present,
Fred Drake4c2533f1999-08-24 22:14:01 +0000242and the except clause's suite is executed. All except clauses must
243have an executable block. When the end of this block
Fred Drakef6669171998-05-06 19:52:49 +0000244is reached, execution continues normally after the entire try
245statement. (This means that if two nested handlers exist for the same
246exception, and the exception occurs in the try clause of the inner
247handler, the outer handler will not handle the exception.)
248
249Before an except clause's suite is executed, details about the
Fred Drake99cd5731999-02-12 20:40:09 +0000250exception are assigned to three variables in the
251\module{sys}\refbimodindex{sys} module: \code{sys.exc_type} receives
252the object identifying the exception; \code{sys.exc_value} receives
253the exception's parameter; \code{sys.exc_traceback} receives a
254traceback object\obindex{traceback} (see section \ref{traceback})
255identifying the point in the program where the exception occurred.
Guido van Rossum5399d681998-07-24 18:51:11 +0000256These details are also available through the \function{sys.exc_info()}
Fred Drake99cd5731999-02-12 20:40:09 +0000257function, which returns a tuple \code{(\var{exc_type}, \var{exc_value},
258\var{exc_traceback})}. Use of the corresponding variables is
Guido van Rossum5399d681998-07-24 18:51:11 +0000259deprecated in favor of this function, since their use is unsafe in a
260threaded program. As of Python 1.5, the variables are restored to
261their previous values (before the call) when returning from a function
262that handled an exception.
Fred Drake99cd5731999-02-12 20:40:09 +0000263\withsubitem{(in module sys)}{\ttindex{exc_type}
264 \ttindex{exc_value}\ttindex{exc_traceback}}
Fred Drakef6669171998-05-06 19:52:49 +0000265
Fred Drake2cba0f62001-01-02 19:22:48 +0000266The optional \keyword{else} clause is executed if and when control
267flows off the end of the \keyword{try} clause.\footnote{
268 Currently, control ``flows off the end'' except in the case of an
269 exception or the execution of a \keyword{return},
270 \keyword{continue}, or \keyword{break} statement.
271} Exceptions in the \keyword{else} clause are not handled by the
272preceding \keyword{except} clauses.
Fred Drakef6669171998-05-06 19:52:49 +0000273\kwindex{else}
Fred Drake2cba0f62001-01-02 19:22:48 +0000274\stindex{return}
275\stindex{break}
276\stindex{continue}
Fred Drakef6669171998-05-06 19:52:49 +0000277
Fred Drake5c07d9b1998-05-14 19:37:06 +0000278The \keyword{try}...\keyword{finally} form specifies a `cleanup' handler. The
279\keyword{try} clause is executed. When no exception occurs, the
280\keyword{finally} clause is executed. When an exception occurs in the
281\keyword{try} clause, the exception is temporarily saved, the
282\keyword{finally} clause is executed, and then the saved exception is
283re-raised. If the \keyword{finally} clause raises another exception or
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000284executes a \keyword{return} or \keyword{break} statement, the saved
285exception is lost. A \keyword{continue} statement is illegal in the
286\keyword{finally} clause. (The reason is a problem with the current
Fred Drake216cbca2002-02-22 15:40:23 +0000287implementation -- this restriction may be lifted in the future). The
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000288exception information is not available to the program during execution of
289the \keyword{finally} clause.
Fred Drakef6669171998-05-06 19:52:49 +0000290\kwindex{finally}
291
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000292When a \keyword{return}, \keyword{break} or \keyword{continue} statement is
293executed in the \keyword{try} suite of a \keyword{try}...\keyword{finally}
294statement, the \keyword{finally} clause is also executed `on the way out.' A
295\keyword{continue} statement is illegal in the \keyword{finally} clause.
296(The reason is a problem with the current implementation --- this
Fred Drakef6669171998-05-06 19:52:49 +0000297restriction may be lifted in the future).
298\stindex{return}
299\stindex{break}
300\stindex{continue}
301
Fred Drake2829f1c2001-06-23 05:27:20 +0000302
Fred Drake61c77281998-07-28 19:34:22 +0000303\section{Function definitions\label{function}}
Fred Drakef6669171998-05-06 19:52:49 +0000304\indexii{function}{definition}
Fred Drake687bde92001-12-27 18:38:10 +0000305\stindex{def}
Fred Drakef6669171998-05-06 19:52:49 +0000306
307A function definition defines a user-defined function object (see
Guido van Rossum5399d681998-07-24 18:51:11 +0000308section \ref{types}):
Fred Drakef6669171998-05-06 19:52:49 +0000309\obindex{user-defined function}
310\obindex{function}
311
Fred Drakecb4638a2001-07-06 22:49:53 +0000312\begin{productionlist}
313 \production{funcdef}
314 {"def" \token{funcname} "(" [\token{parameter_list}] ")"
315 ":" \token{suite}}
316 \production{parameter_list}
Fred Drake53815882002-03-15 23:21:37 +0000317 {(\token{defparameter} ",")*}
318 \productioncont{("*" \token{identifier} [, "**" \token{identifier}]}
319 \productioncont{| "**" \token{identifier}
320 | \token{defparameter} [","])}
Fred Drakecb4638a2001-07-06 22:49:53 +0000321 \production{defparameter}
322 {\token{parameter} ["=" \token{expression}]}
323 \production{sublist}
324 {\token{parameter} ("," \token{parameter})* [","]}
325 \production{parameter}
326 {\token{identifier} | "(" \token{sublist} ")"}
327 \production{funcname}
328 {\token{identifier}}
329\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000330
331A function definition is an executable statement. Its execution binds
Guido van Rossum5399d681998-07-24 18:51:11 +0000332the function name in the current local namespace to a function object
Fred Drakef6669171998-05-06 19:52:49 +0000333(a wrapper around the executable code for the function). This
Guido van Rossum5399d681998-07-24 18:51:11 +0000334function object contains a reference to the current global namespace
335as the global namespace to be used when the function is called.
Fred Drakef6669171998-05-06 19:52:49 +0000336\indexii{function}{name}
337\indexii{name}{binding}
338
339The function definition does not execute the function body; this gets
340executed only when the function is called.
341
Guido van Rossum5399d681998-07-24 18:51:11 +0000342When one or more top-level parameters have the form \var{parameter}
343\code{=} \var{expression}, the function is said to have ``default
Guido van Rossume0394391998-12-04 19:37:10 +0000344parameter values.'' For a parameter with a
Guido van Rossum5399d681998-07-24 18:51:11 +0000345default value, the corresponding argument may be omitted from a call,
346in which case the parameter's default value is substituted. If a
347parameter has a default value, all following parameters must also have
348a default value --- this is a syntactic restriction that is not
Fred Drakee15956b2000-04-03 04:51:13 +0000349expressed by the grammar.
Fred Drakef6669171998-05-06 19:52:49 +0000350\indexiii{default}{parameter}{value}
351
Guido van Rossume0394391998-12-04 19:37:10 +0000352\strong{Default parameter values are evaluated when the function
353definition is executed.} This means that the expression is evaluated
354once, when the function is defined, and that that same
355``pre-computed'' value is used for each call. This is especially
356important to understand when a default parameter is a mutable object,
357such as a list or a dictionary: if the function modifies the object
358(e.g. by appending an item to a list), the default value is in effect
359modified. This is generally not what was intended. A way around this
360is to use \code{None} as the default, and explicitly test for it in
361the body of the function, e.g.:
362
363\begin{verbatim}
364def whats_on_the_telly(penguin=None):
365 if penguin is None:
366 penguin = []
367 penguin.append("property of the zoo")
368 return penguin
369\end{verbatim}
370
Guido van Rossum5399d681998-07-24 18:51:11 +0000371Function call semantics are described in more detail in section
372\ref{calls}.
373A function call always assigns values to all parameters mentioned in
374the parameter list, either from position arguments, from keyword
375arguments, or from default values. If the form ``\code{*identifier}''
376is present, it is initialized to a tuple receiving any excess
377positional parameters, defaulting to the empty tuple. If the form
378``\code{**identifier}'' is present, it is initialized to a new
379dictionary receiving any excess keyword arguments, defaulting to a
380new empty dictionary.
Fred Drakef6669171998-05-06 19:52:49 +0000381
Fred Drakef6669171998-05-06 19:52:49 +0000382It is also possible to create anonymous functions (functions not bound
383to a name), for immediate use in expressions. This uses lambda forms,
Guido van Rossum5399d681998-07-24 18:51:11 +0000384described in section \ref{lambda}. Note that the lambda form is
385merely a shorthand for a simplified function definition; a function
386defined in a ``\keyword{def}'' statement can be passed around or
387assigned to another name just like a function defined by a lambda
388form. The ``\keyword{def}'' form is actually more powerful since it
389allows the execution of multiple statements.
Fred Drakef6669171998-05-06 19:52:49 +0000390\indexii{lambda}{form}
391
Jeremy Hylton1824b592002-04-01 21:30:15 +0000392\strong{Programmer's note:} Functions are first-class objects. A
393``\code{def}'' form executed inside a function definition defines a
394local function that can be returned or passed around. Free variables
395used in the nested function can access the local variables of the
396function containing the def. See section \ref{naming} for details.
Guido van Rossum5399d681998-07-24 18:51:11 +0000397
Fred Drake2829f1c2001-06-23 05:27:20 +0000398
Fred Drake61c77281998-07-28 19:34:22 +0000399\section{Class definitions\label{class}}
Fred Drakef6669171998-05-06 19:52:49 +0000400\indexii{class}{definition}
Fred Drake687bde92001-12-27 18:38:10 +0000401\stindex{class}
Fred Drakef6669171998-05-06 19:52:49 +0000402
403A class definition defines a class object (see section \ref{types}):
404\obindex{class}
405
Fred Drakecb4638a2001-07-06 22:49:53 +0000406\begin{productionlist}
407 \production{classdef}
408 {"class" \token{classname} [\token{inheritance}] ":"
409 \token{suite}}
410 \production{inheritance}
411 {"(" [\token{expression_list}] ")"}
412 \production{classname}
413 {\token{identifier}}
414\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000415
416A class definition is an executable statement. It first evaluates the
417inheritance list, if present. Each item in the inheritance list
418should evaluate to a class object. The class's suite is then executed
Jeremy Hylton88955cb2002-04-01 21:34:28 +0000419in a new execution frame (see section \ref{naming}), using a newly
Guido van Rossum5399d681998-07-24 18:51:11 +0000420created local namespace and the original global namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000421(Usually, the suite contains only function definitions.) When the
422class's suite finishes execution, its execution frame is discarded but
Guido van Rossum5399d681998-07-24 18:51:11 +0000423its local namespace is saved. A class object is then created using
424the inheritance list for the base classes and the saved local
425namespace for the attribute dictionary. The class name is bound to this
426class object in the original local namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000427\index{inheritance}
428\indexii{class}{name}
429\indexii{name}{binding}
430\indexii{execution}{frame}
Guido van Rossum5399d681998-07-24 18:51:11 +0000431
432\strong{Programmer's note:} variables defined in the class definition
433are class variables; they are shared by all instances. To define
434instance variables, they must be given a value in the the
435\method{__init__()} method or in another method. Both class and
436instance variables are accessible through the notation
Fred Drake7c116d72001-05-10 15:09:36 +0000437``\code{self.name}'', and an instance variable hides a class variable
Guido van Rossum5399d681998-07-24 18:51:11 +0000438with the same name when accessed in this way. Class variables with
439immutable values can be used as defaults for instance variables.