blob: 4c7487b6dfa0d9d95c9f21db67b0614d074870b1 [file] [log] [blame]
Fred Drake011f6fc1999-04-14 12:52:14 +00001\chapter{Simple statements \label{simple}}
Fred Drakef6669171998-05-06 19:52:49 +00002\indexii{simple}{statement}
3
4Simple statements are comprised within a single logical line.
5Several simple statements may occur on a single line separated
6by semicolons. The syntax for simple statements is:
7
Fred Drakecb4638a2001-07-06 22:49:53 +00008\begin{productionlist}
Fred Drake53815882002-03-15 23:21:37 +00009 \production{simple_stmt}{\token{expression_stmt}}
10 \productioncont{| \token{assert_stmt}}
11 \productioncont{| \token{assignment_stmt}}
12 \productioncont{| \token{augmented_assignment_stmt}}
13 \productioncont{| \token{pass_stmt}}
14 \productioncont{| \token{del_stmt}}
Fred Drake53815882002-03-15 23:21:37 +000015 \productioncont{| \token{return_stmt}}
16 \productioncont{| \token{yield_stmt}}
17 \productioncont{| \token{raise_stmt}}
18 \productioncont{| \token{break_stmt}}
19 \productioncont{| \token{continue_stmt}}
20 \productioncont{| \token{import_stmt}}
21 \productioncont{| \token{global_stmt}}
Fred Drakecb4638a2001-07-06 22:49:53 +000022\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000023
Fred Drake2829f1c2001-06-23 05:27:20 +000024
Fred Drake011f6fc1999-04-14 12:52:14 +000025\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000026\indexii{expression}{statement}
27
28Expression statements are used (mostly interactively) to compute and
29write a value, or (usually) to call a procedure (a function that
30returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000031\code{None}). Other uses of expression statements are allowed and
32occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000033
Fred Drakecb4638a2001-07-06 22:49:53 +000034\begin{productionlist}
35 \production{expression_stmt}
36 {\token{expression_list}}
37\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000038
Guido van Rossum56c20131998-07-24 18:25:38 +000039An expression statement evaluates the expression list (which may be a
40single expression).
Fred Drakef6669171998-05-06 19:52:49 +000041\indexii{expression}{list}
42
43In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000044to a string using the built-in \function{repr()}\bifuncindex{repr}
45function and the resulting string is written to standard output (see
Fred Drakec2f496a2001-12-05 05:46:25 +000046section~\ref{print}) on a line by itself. (Expression statements
47yielding \code{None} are not written, so that procedure calls do not
48cause any output.)
Fred Drake7a700b82004-01-01 05:43:53 +000049\obindex{None}
Fred Drakef6669171998-05-06 19:52:49 +000050\indexii{string}{conversion}
51\index{output}
52\indexii{standard}{output}
53\indexii{writing}{values}
54\indexii{procedure}{call}
55
Fred Drake2829f1c2001-06-23 05:27:20 +000056
Fred Drake011f6fc1999-04-14 12:52:14 +000057\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000058
Fred Drake011f6fc1999-04-14 12:52:14 +000059Assert statements\stindex{assert} are a convenient way to insert
60debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000061
Fred Drakecb4638a2001-07-06 22:49:53 +000062\begin{productionlist}
Fred Drake007fadd2003-03-31 14:53:03 +000063 \production{assert_stmt}
Fred Drakecb4638a2001-07-06 22:49:53 +000064 {"assert" \token{expression} ["," \token{expression}]}
65\end{productionlist}
Guido van Rossum56c20131998-07-24 18:25:38 +000066
Fred Drake011f6fc1999-04-14 12:52:14 +000067The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000068
69\begin{verbatim}
70if __debug__:
71 if not expression: raise AssertionError
72\end{verbatim}
73
Fred Drake011f6fc1999-04-14 12:52:14 +000074The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000075equivalent to
76
77\begin{verbatim}
78if __debug__:
79 if not expression1: raise AssertionError, expression2
80\end{verbatim}
81
82These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000083\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000084variables with those names. In the current implementation, the
Johannes Gijsbersf4a70f32004-12-12 16:52:40 +000085built-in variable \code{__debug__} is \code{True} under normal
86circumstances, \code{False} when optimization is requested (command line
87option -O). The current code generator emits no code for an assert
88statement when optimization is requested at compile time. Note that it
89is unnecessary to include the source code for the expression that failed
90in the error message;
Guido van Rossum56c20131998-07-24 18:25:38 +000091it will be displayed as part of the stack trace.
92
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000093Assignments to \code{__debug__} are illegal. The value for the
94built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000095
Fred Drake2829f1c2001-06-23 05:27:20 +000096
Fred Drake011f6fc1999-04-14 12:52:14 +000097\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000098
Fred Drake011f6fc1999-04-14 12:52:14 +000099Assignment statements\indexii{assignment}{statement} are used to
100(re)bind names to values and to modify attributes or items of mutable
101objects:
Fred Drakef6669171998-05-06 19:52:49 +0000102\indexii{binding}{name}
103\indexii{rebinding}{name}
104\obindex{mutable}
105\indexii{attribute}{assignment}
106
Fred Drakecb4638a2001-07-06 22:49:53 +0000107\begin{productionlist}
108 \production{assignment_stmt}
109 {(\token{target_list} "=")+ \token{expression_list}}
110 \production{target_list}
111 {\token{target} ("," \token{target})* [","]}
112 \production{target}
Fred Drake53815882002-03-15 23:21:37 +0000113 {\token{identifier}}
114 \productioncont{| "(" \token{target_list} ")"}
115 \productioncont{| "[" \token{target_list} "]"}
116 \productioncont{| \token{attributeref}}
117 \productioncont{| \token{subscription}}
118 \productioncont{| \token{slicing}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000119\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000120
Fred Drakec2f496a2001-12-05 05:46:25 +0000121(See section~\ref{primaries} for the syntax definitions for the last
Fred Drakef6669171998-05-06 19:52:49 +0000122three symbols.)
123
124An assignment statement evaluates the expression list (remember that
125this can be a single expression or a comma-separated list, the latter
126yielding a tuple) and assigns the single resulting object to each of
127the target lists, from left to right.
128\indexii{expression}{list}
129
130Assignment is defined recursively depending on the form of the target
131(list). When a target is part of a mutable object (an attribute
132reference, subscription or slicing), the mutable object must
133ultimately perform the assignment and decide about its validity, and
134may raise an exception if the assignment is unacceptable. The rules
135observed by various types and the exceptions raised are given with the
Fred Drakec2f496a2001-12-05 05:46:25 +0000136definition of the object types (see section~\ref{types}).
Fred Drakef6669171998-05-06 19:52:49 +0000137\index{target}
138\indexii{target}{list}
139
140Assignment of an object to a target list is recursively defined as
141follows.
142\indexiii{target}{list}{assignment}
143
144\begin{itemize}
145\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000146If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000147target.
148
149\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000150If the target list is a comma-separated list of targets: The object
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000151must be a sequence with the same number of items as there are
Guido van Rossum56c20131998-07-24 18:25:38 +0000152targets in the target list, and the items are assigned, from left to
153right, to the corresponding targets. (This rule is relaxed as of
154Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000155strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000156now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000157
158\end{itemize}
159
160Assignment of an object to a single target is recursively defined as
161follows.
162
163\begin{itemize} % nested
164
165\item
166If the target is an identifier (name):
167
168\begin{itemize}
169
170\item
171If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000172code block: the name is bound to the object in the current local
173namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000174\stindex{global}
175
176\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000177Otherwise: the name is bound to the object in the current global
178namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000179
180\end{itemize} % nested
181
Guido van Rossum56c20131998-07-24 18:25:38 +0000182The name is rebound if it was already bound. This may cause the
183reference count for the object previously bound to the name to reach
184zero, causing the object to be deallocated and its
185destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000186
187\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000188If the target is a target list enclosed in parentheses or in square
189brackets: The object must be a sequence with the same number of items
190as there are targets in the target list, and its items are assigned,
191from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000192
193\item
194If the target is an attribute reference: The primary expression in the
195reference is evaluated. It should yield an object with assignable
196attributes; if this is not the case, \exception{TypeError} is raised. That
197object is then asked to assign the assigned object to the given
198attribute; if it cannot perform the assignment, it raises an exception
199(usually but not necessarily \exception{AttributeError}).
200\indexii{attribute}{assignment}
201
202\item
203If the target is a subscription: The primary expression in the
204reference is evaluated. It should yield either a mutable sequence
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000205object (such as a list) or a mapping object (such as a dictionary). Next,
Guido van Rossum56c20131998-07-24 18:25:38 +0000206the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000207\indexii{subscription}{assignment}
208\obindex{mutable}
209
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000210If the primary is a mutable sequence object (such as a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000211must yield a plain integer. If it is negative, the sequence's length
212is added to it. The resulting value must be a nonnegative integer
213less than the sequence's length, and the sequence is asked to assign
214the assigned object to its item with that index. If the index is out
215of range, \exception{IndexError} is raised (assignment to a subscripted
216sequence cannot add new items to a list).
217\obindex{sequence}
218\obindex{list}
219
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000220If the primary is a mapping object (such as a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000221have a type compatible with the mapping's key type, and the mapping is
222then asked to create a key/datum pair which maps the subscript to
223the assigned object. This can either replace an existing key/value
224pair with the same key value, or insert a new key/value pair (if no
225key with the same value existed).
226\obindex{mapping}
227\obindex{dictionary}
228
229\item
230If the target is a slicing: The primary expression in the reference is
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000231evaluated. It should yield a mutable sequence object (such as a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000232assigned object should be a sequence object of the same type. Next,
233the lower and upper bound expressions are evaluated, insofar they are
234present; defaults are zero and the sequence's length. The bounds
235should evaluate to (small) integers. If either bound is negative, the
236sequence's length is added to it. The resulting bounds are clipped to
237lie between zero and the sequence's length, inclusive. Finally, the
238sequence object is asked to replace the slice with the items of the
239assigned sequence. The length of the slice may be different from the
240length of the assigned sequence, thus changing the length of the
241target sequence, if the object allows it.
242\indexii{slicing}{assignment}
243
244\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000245
Fred Drakef6669171998-05-06 19:52:49 +0000246(In the current implementation, the syntax for targets is taken
247to be the same as for expressions, and invalid syntax is rejected
248during the code generation phase, causing less detailed error
249messages.)
250
251WARNING: Although the definition of assignment implies that overlaps
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000252between the left-hand side and the right-hand side are `safe' (for example
Fred Drake011f6fc1999-04-14 12:52:14 +0000253\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000254collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000255following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000256
257\begin{verbatim}
258x = [0, 1]
259i = 0
260i, x[i] = 1, 2
261print x
262\end{verbatim}
263
264
Fred Drake53815882002-03-15 23:21:37 +0000265\subsection{Augmented assignment statements \label{augassign}}
Fred Drake31f55502000-09-12 20:32:18 +0000266
267Augmented assignment is the combination, in a single statement, of a binary
268operation and an assignment statement:
269\indexii{augmented}{assignment}
270\index{statement!assignment, augmented}
271
Fred Drakecb4638a2001-07-06 22:49:53 +0000272\begin{productionlist}
273 \production{augmented_assignment_stmt}
274 {\token{target} \token{augop} \token{expression_list}}
275 \production{augop}
Fred Drake53815882002-03-15 23:21:37 +0000276 {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}
Fred Drake2269d862004-11-11 06:14:05 +0000277 % The empty groups below prevent conversion to guillemets.
278 \productioncont{| ">{}>=" | "<{}<=" | "\&=" | "\textasciicircum=" | "|="}
Fred Drakecb4638a2001-07-06 22:49:53 +0000279\end{productionlist}
Fred Drake31f55502000-09-12 20:32:18 +0000280
Fred Drakec2f496a2001-12-05 05:46:25 +0000281(See section~\ref{primaries} for the syntax definitions for the last
Fred Drake31f55502000-09-12 20:32:18 +0000282three symbols.)
283
Fred Draked68442b2000-09-21 22:01:36 +0000284An augmented assignment evaluates the target (which, unlike normal
285assignment statements, cannot be an unpacking) and the expression
286list, performs the binary operation specific to the type of assignment
287on the two operands, and assigns the result to the original
288target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000289
290An augmented assignment expression like \code{x += 1} can be rewritten as
291\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
292augmented version, \code{x} is only evaluated once. Also, when possible, the
293actual operation is performed \emph{in-place}, meaning that rather than
294creating a new object and assigning that to the target, the old object is
295modified instead.
296
297With the exception of assigning to tuples and multiple targets in a single
298statement, the assignment done by augmented assignment statements is handled
299the same way as normal assignments. Similarly, with the exception of the
Fred Drakec2f496a2001-12-05 05:46:25 +0000300possible \emph{in-place} behavior, the binary operation performed by
Fred Drake31f55502000-09-12 20:32:18 +0000301augmented assignment is the same as the normal binary operations.
302
Raymond Hettinger04e7e0c2002-06-25 13:36:41 +0000303For targets which are attribute references, the initial value is
304retrieved with a \method{getattr()} and the result is assigned with a
305\method{setattr()}. Notice that the two methods do not necessarily
306refer to the same variable. When \method{getattr()} refers to a class
307variable, \method{setattr()} still writes to an instance variable.
308For example:
309
310\begin{verbatim}
311class A:
312 x = 3 # class variable
313a = A()
314a.x += 1 # writes a.x as 4 leaving A.x as 3
315\end{verbatim}
316
Fred Drake31f55502000-09-12 20:32:18 +0000317
Fred Drake011f6fc1999-04-14 12:52:14 +0000318\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000319\stindex{pass}
320
Fred Drakecb4638a2001-07-06 22:49:53 +0000321\begin{productionlist}
322 \production{pass_stmt}
323 {"pass"}
324\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000325
326\keyword{pass} is a null operation --- when it is executed, nothing
327happens. It is useful as a placeholder when a statement is
328required syntactically, but no code needs to be executed, for example:
329\indexii{null}{operation}
330
331\begin{verbatim}
332def f(arg): pass # a function that does nothing (yet)
333
334class C: pass # a class with no methods (yet)
335\end{verbatim}
336
Fred Drake2829f1c2001-06-23 05:27:20 +0000337
Fred Drake011f6fc1999-04-14 12:52:14 +0000338\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000339\stindex{del}
340
Fred Drakecb4638a2001-07-06 22:49:53 +0000341\begin{productionlist}
342 \production{del_stmt}
343 {"del" \token{target_list}}
344\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000345
346Deletion is recursively defined very similar to the way assignment is
347defined. Rather that spelling it out in full details, here are some
348hints.
349\indexii{deletion}{target}
350\indexiii{deletion}{target}{list}
351
352Deletion of a target list recursively deletes each target, from left
353to right.
354
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000355Deletion of a name removes the binding of that name
Guido van Rossum56c20131998-07-24 18:25:38 +0000356from the local or global namespace, depending on whether the name
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000357occurs in a \keyword{global} statement in the same code block. If the
358name is unbound, a \exception{NameError} exception will be raised.
Fred Drakef6669171998-05-06 19:52:49 +0000359\stindex{global}
360\indexii{unbinding}{name}
361
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000362It is illegal to delete a name from the local namespace if it occurs
Michael W. Hudson495afea2002-06-17 12:51:57 +0000363as a free variable\indexii{free}{variable} in a nested block.
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000364
Fred Drakef6669171998-05-06 19:52:49 +0000365Deletion of attribute references, subscriptions and slicings
366is passed to the primary object involved; deletion of a slicing
367is in general equivalent to assignment of an empty slice of the
368right type (but even this is determined by the sliced object).
369\indexii{attribute}{deletion}
370
Fred Drake2829f1c2001-06-23 05:27:20 +0000371
Fred Drake011f6fc1999-04-14 12:52:14 +0000372\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000373\stindex{return}
374
Fred Drakecb4638a2001-07-06 22:49:53 +0000375\begin{productionlist}
376 \production{return_stmt}
377 {"return" [\token{expression_list}]}
378\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000379
380\keyword{return} may only occur syntactically nested in a function
381definition, not within a nested class definition.
382\indexii{function}{definition}
383\indexii{class}{definition}
384
Guido van Rossum56c20131998-07-24 18:25:38 +0000385If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000386is substituted.
387
Guido van Rossum56c20131998-07-24 18:25:38 +0000388\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000389list (or \code{None}) as return value.
390
391When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000392with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000393before really leaving the function.
394\kwindex{finally}
395
Fred Drakee31e9ce2001-12-11 21:10:08 +0000396In a generator function, the \keyword{return} statement is not allowed
397to include an \grammartoken{expression_list}. In that context, a bare
398\keyword{return} indicates that the generator is done and will cause
399\exception{StopIteration} to be raised.
400
401
402\section{The \keyword{yield} statement \label{yield}}
403\stindex{yield}
404
405\begin{productionlist}
406 \production{yield_stmt}
407 {"yield" \token{expression_list}}
408\end{productionlist}
409
410\index{generator!function}
411\index{generator!iterator}
412\index{function!generator}
413\exindex{StopIteration}
414
415The \keyword{yield} statement is only used when defining a generator
416function, and is only used in the body of the generator function.
417Using a \keyword{yield} statement in a function definition is
418sufficient to cause that definition to create a generator function
419instead of a normal function.
420
421When a generator function is called, it returns an iterator known as a
422generator iterator, or more commonly, a generator. The body of the
423generator function is executed by calling the generator's
424\method{next()} method repeatedly until it raises an exception.
425
426When a \keyword{yield} statement is executed, the state of the
427generator is frozen and the value of \grammartoken{expression_list} is
428returned to \method{next()}'s caller. By ``frozen'' we mean that all
429local state is retained, including the current bindings of local
430variables, the instruction pointer, and the internal evaluation stack:
431enough information is saved so that the next time \method{next()} is
432invoked, the function can proceed exactly as if the \keyword{yield}
433statement were just another external call.
434
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435As of Python version 2.5, the \keyword{yield} statement is now
436allowed in the \keyword{try} clause of a \keyword{try} ...\
437\keyword{finally} construct. If the generator is not resumed before
438it is finalized (by reaching a zero reference count or by being garbage
439collected), the generator-iterator's \method{close()} method will be
440called, allowing any pending \keyword{finally} clauses to execute.
Fred Drakee31e9ce2001-12-11 21:10:08 +0000441
Fred Drake08d752c2001-12-14 22:55:14 +0000442\begin{notice}
443In Python 2.2, the \keyword{yield} statement is only allowed
Fred Drake8d0645c2001-12-12 06:06:43 +0000444when the \code{generators} feature has been enabled. It will always
Raymond Hettinger68804312005-01-01 00:28:46 +0000445be enabled in Python 2.3. This \code{__future__} import statement can
Fred Drake08d752c2001-12-14 22:55:14 +0000446be used to enable the feature:
Fred Drake8d0645c2001-12-12 06:06:43 +0000447
448\begin{verbatim}
449from __future__ import generators
450\end{verbatim}
Fred Drake08d752c2001-12-14 22:55:14 +0000451\end{notice}
Fred Drake8d0645c2001-12-12 06:06:43 +0000452
453
Fred Drakee31e9ce2001-12-11 21:10:08 +0000454\begin{seealso}
455 \seepep{0255}{Simple Generators}
456 {The proposal for adding generators and the \keyword{yield}
457 statement to Python.}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458
459 \seepep{0342}{Coroutines via Enhanced Generators}
460 {The proposal that, among other generator enhancements,
461 proposed allowing \keyword{yield} to appear inside a
462 \keyword{try} ... \keyword{finally} block.}
Fred Drakee31e9ce2001-12-11 21:10:08 +0000463\end{seealso}
464
Fred Drake2829f1c2001-06-23 05:27:20 +0000465
Fred Drake011f6fc1999-04-14 12:52:14 +0000466\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000467\stindex{raise}
468
Fred Drakecb4638a2001-07-06 22:49:53 +0000469\begin{productionlist}
470 \production{raise_stmt}
471 {"raise" [\token{expression} ["," \token{expression}
472 ["," \token{expression}]]]}
473\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000474
Guido van Rossum56c20131998-07-24 18:25:38 +0000475If no expressions are present, \keyword{raise} re-raises the last
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000476exception that was active in the current scope. If no exception is
Raymond Hettingerbee0d462005-10-03 16:39:51 +0000477active in the current scope, a \exception{TypeError} exception is
478raised indicating that this is an error (if running under IDLE, a
Neal Norwitzc0d11252005-10-04 03:43:43 +0000479\exception{Queue.Empty} exception is raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000480\index{exception}
481\indexii{raising}{exception}
482
Fred Drake81932e22002-06-20 20:55:29 +0000483Otherwise, \keyword{raise} evaluates the expressions to get three
484objects, using \code{None} as the value of omitted expressions. The
485first two objects are used to determine the \emph{type} and
486\emph{value} of the exception.
Fred Drakef6669171998-05-06 19:52:49 +0000487
Fred Drake81932e22002-06-20 20:55:29 +0000488If the first object is an instance, the type of the exception is the
Fred Drake8bd62af2003-01-25 03:47:35 +0000489class of the instance, the instance itself is the value, and the
Fred Drake81932e22002-06-20 20:55:29 +0000490second object must be \code{None}.
491
492If the first object is a class, it becomes the type of the exception.
493The second object is used to determine the exception value: If it is
494an instance of the class, the instance becomes the exception value.
495If the second object is a tuple, it is used as the argument list for
496the class constructor; if it is \code{None}, an empty argument list is
497used, and any other object is treated as a single argument to the
498constructor. The instance so created by calling the constructor is
499used as the exception value.
500
Fred Drake81932e22002-06-20 20:55:29 +0000501If a third object is present and not \code{None}, it must be a
502traceback\obindex{traceback} object (see section~\ref{traceback}), and
503it is substituted instead of the current location as the place where
504the exception occurred. If the third object is present and not a
505traceback object or \code{None}, a \exception{TypeError} exception is
506raised. The three-expression form of \keyword{raise} is useful to
507re-raise an exception transparently in an except clause, but
508\keyword{raise} with no expressions should be preferred if the
509exception to be re-raised was the most recently active exception in
510the current scope.
511
Fred Drakee7097e02002-10-18 15:18:18 +0000512Additional information on exceptions can be found in
513section~\ref{exceptions}, and information about handling exceptions is
514in section~\ref{try}.
Fred Drakef6669171998-05-06 19:52:49 +0000515
Fred Drake2829f1c2001-06-23 05:27:20 +0000516
Fred Drake011f6fc1999-04-14 12:52:14 +0000517\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000518\stindex{break}
519
Fred Drakecb4638a2001-07-06 22:49:53 +0000520\begin{productionlist}
521 \production{break_stmt}
522 {"break"}
523\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000524
525\keyword{break} may only occur syntactically nested in a \keyword{for}
526or \keyword{while} loop, but not nested in a function or class definition
527within that loop.
528\stindex{for}
529\stindex{while}
530\indexii{loop}{statement}
531
532It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000533\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000534\kwindex{else}
535
536If a \keyword{for} loop is terminated by \keyword{break}, the loop control
537target keeps its current value.
538\indexii{loop control}{target}
539
540When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000541with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000542before really leaving the loop.
543\kwindex{finally}
544
Fred Drake2829f1c2001-06-23 05:27:20 +0000545
Fred Drake011f6fc1999-04-14 12:52:14 +0000546\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000547\stindex{continue}
548
Fred Drakecb4638a2001-07-06 22:49:53 +0000549\begin{productionlist}
550 \production{continue_stmt}
551 {"continue"}
552\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000553
554\keyword{continue} may only occur syntactically nested in a \keyword{for} or
555\keyword{while} loop, but not nested in a function or class definition or
Neal Norwitz19f6b862005-10-04 03:37:29 +0000556\keyword{finally} statement within that loop.\footnote{It may
Guido van Rossum56c20131998-07-24 18:25:38 +0000557occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000558restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000559laziness and will eventually be lifted.}
560It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000561\stindex{for}
562\stindex{while}
563\indexii{loop}{statement}
564\kwindex{finally}
565
Fred Drake2829f1c2001-06-23 05:27:20 +0000566
Fred Drake011f6fc1999-04-14 12:52:14 +0000567\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000568\stindex{import}
Fred Drakeb3be52e2003-07-15 21:37:58 +0000569\index{module!importing}
570\indexii{name}{binding}
571\kwindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000572
Fred Drakecb4638a2001-07-06 22:49:53 +0000573\begin{productionlist}
574 \production{import_stmt}
575 {"import" \token{module} ["as" \token{name}]
Fred Drake53815882002-03-15 23:21:37 +0000576 ( "," \token{module} ["as" \token{name}] )*}
577 \productioncont{| "from" \token{module} "import" \token{identifier}
578 ["as" \token{name}]}
579 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )*}
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000580 \productioncont{| "from" \token{module} "import" "(" \token{identifier}
581 ["as" \token{name}]}
582 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )* [","] ")"}
Fred Drake53815882002-03-15 23:21:37 +0000583 \productioncont{| "from" \token{module} "import" "*"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000584 \production{module}
585 {(\token{identifier} ".")* \token{identifier}}
586\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000587
588Import statements are executed in two steps: (1) find a module, and
589initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000590namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000591The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000592identifier in the list. The form with \keyword{from} performs step
593(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000594
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000595In this context, to ``initialize'' a built-in or extension module means to
596call an initialization function that the module must provide for the purpose
597(in the reference implementation, the function's name is obtained by
598prepending string ``init'' to the module's name); to ``initialize'' a
599Python-coded module means to execute the module's body.
600
601The system maintains a table of modules that have been or are being
602initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000603indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000604accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000605this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000606definition is started. When a module is found, it is loaded. Details
607of the module searching and loading process are implementation and
608platform specific. It generally involves searching for a ``built-in''
609module with the given name and then searching a list of locations
610given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000611\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000612\ttindex{sys.modules}
613\indexii{module}{name}
614\indexii{built-in}{module}
615\indexii{user-defined}{module}
616\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000617\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000618\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000619
Fred Draked51ce7d2003-07-15 22:03:00 +0000620If a built-in module is found,\indexii{module}{initialization} its
621built-in initialization code is executed and step (1) is finished. If
622no matching file is found,
623\exception{ImportError}\exindex{ImportError} is raised.
624\index{code block}If a file is found, it is parsed,
Fred Drakef6669171998-05-06 19:52:49 +0000625yielding an executable code block. If a syntax error occurs,
Fred Draked51ce7d2003-07-15 22:03:00 +0000626\exception{SyntaxError}\exindex{SyntaxError} is raised. Otherwise, an
627empty module of the given name is created and inserted in the module
628table, and then the code block is executed in the context of this
629module. Exceptions during this execution terminate step (1).
Fred Drakef6669171998-05-06 19:52:49 +0000630
631When step (1) finishes without raising an exception, step (2) can
632begin.
633
Fred Drake859eb622001-03-06 07:34:00 +0000634The first form of \keyword{import} statement binds the module name in
635the local namespace to the module object, and then goes on to import
636the next identifier, if any. If the module name is followed by
637\keyword{as}, the name following \keyword{as} is used as the local
Martin v. Löwis13dd9d92003-01-16 11:30:08 +0000638name for the module.
Thomas Wouters8bad6122000-08-19 20:55:02 +0000639
Thomas Wouters52152252000-08-17 22:55:00 +0000640The \keyword{from} form does not bind the module name: it goes through the
641list of identifiers, looks each one of them up in the module found in step
642(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000643As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000644supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000645\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drake08fd5152001-10-24 19:50:31 +0000646by a star (\character{*}), all public names defined in the module are
647bound in the local namespace of the \keyword{import} statement..
Fred Drakef6669171998-05-06 19:52:49 +0000648\indexii{name}{binding}
649\exindex{ImportError}
650
Fred Drake08fd5152001-10-24 19:50:31 +0000651The \emph{public names} defined by a module are determined by checking
652the module's namespace for a variable named \code{__all__}; if
653defined, it must be a sequence of strings which are names defined or
654imported by that module. The names given in \code{__all__} are all
655considered public and are required to exist. If \code{__all__} is not
656defined, the set of public names includes all names found in the
657module's namespace which do not begin with an underscore character
Raymond Hettinger1772f172003-01-06 12:54:54 +0000658(\character{_}). \code{__all__} should contain the entire public API.
659It is intended to avoid accidentally exporting items that are not part
660of the API (such as library modules which were imported and used within
661the module).
Fred Drake27cae1f2002-12-07 16:00:00 +0000662\withsubitem{(optional module attribute)}{\ttindex{__all__}}
Fred Drake08fd5152001-10-24 19:50:31 +0000663
Jeremy Hyltonf0c1f1b2002-04-01 21:19:44 +0000664The \keyword{from} form with \samp{*} may only occur in a module
665scope. If the wild card form of import --- \samp{import *} --- is
666used in a function and the function contains or is a nested block with
667free variables, the compiler will raise a \exception{SyntaxError}.
668
Fred Drakef6669171998-05-06 19:52:49 +0000669\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000670\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000671
Fred Drake246837d1998-07-24 20:28:22 +0000672\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000673when the module names contains one or more dots, the module search
674path is carried out differently. The sequence of identifiers up to
675the last dot is used to find a ``package''\index{packages}; the final
676identifier is then searched inside the package. A package is
677generally a subdirectory of a directory on \code{sys.path} that has a
678file \file{__init__.py}.\ttindex{__init__.py}
679%
680[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000681\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000682about how the module search works from inside a package.]
683
Fred Drake08fd5152001-10-24 19:50:31 +0000684The built-in function \function{__import__()} is provided to support
685applications that determine which modules need to be loaded
686dynamically; refer to \ulink{Built-in
687Functions}{../lib/built-in-funcs.html} in the
688\citetitle[../lib/lib.html]{Python Library Reference} for additional
689information.
Guido van Rossum56c20131998-07-24 18:25:38 +0000690\bifuncindex{__import__}
691
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000692\subsection{Future statements \label{future}}
693
694A \dfn{future statement}\indexii{future}{statement} is a directive to
695the compiler that a particular module should be compiled using syntax
696or semantics that will be available in a specified future release of
697Python. The future statement is intended to ease migration to future
698versions of Python that introduce incompatible changes to the
699language. It allows use of the new features on a per-module basis
700before the release in which the feature becomes standard.
701
702\begin{productionlist}[*]
703 \production{future_statement}
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000704 {"from" "__future__" "import" feature ["as" name] ("," feature ["as" name])*}
705 \productioncont{| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])* [","] ")"}
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000706 \production{feature}{identifier}
707 \production{name}{identifier}
708\end{productionlist}
709
710A future statement must appear near the top of the module. The only
711lines that can appear before a future statement are:
712
713\begin{itemize}
714
715\item the module docstring (if any),
716\item comments,
717\item blank lines, and
718\item other future statements.
719
720\end{itemize}
721
722The features recognized by Python 2.3 are \samp{generators},
723\samp{division} and \samp{nested_scopes}. \samp{generators} and
724\samp{nested_scopes} are redundant in 2.3 because they are always
725enabled.
726
727A future statement is recognized and treated specially at compile
728time: Changes to the semantics of core constructs are often
729implemented by generating different code. It may even be the case
730that a new feature introduces new incompatible syntax (such as a new
731reserved word), in which case the compiler may need to parse the
732module differently. Such decisions cannot be pushed off until
733runtime.
734
735For any given release, the compiler knows which feature names have been
736defined, and raises a compile-time error if a future statement contains
737a feature not known to it.
738
739The direct runtime semantics are the same as for any import statement:
740there is a standard module \module{__future__}, described later, and
741it will be imported in the usual way at the time the future statement
742is executed.
743
744The interesting runtime semantics depend on the specific feature
745enabled by the future statement.
746
747Note that there is nothing special about the statement:
748
749\begin{verbatim}
750import __future__ [as name]
751\end{verbatim}
752
753That is not a future statement; it's an ordinary import statement with
754no special semantics or syntax restrictions.
755
Georg Brandl7cae87c2006-09-06 06:51:57 +0000756Code compiled by calls to the builtin functions \function{exec()},
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000757\function{compile()} and \function{execfile()} that occur in a module
758\module{M} containing a future statement will, by default, use the new
759syntax or semantics associated with the future statement. This can,
760starting with Python 2.2 be controlled by optional arguments to
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761\function{compile()} --- see the documentation of that function in the
762\citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
763details.
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000764
765A future statement typed at an interactive interpreter prompt will
766take effect for the rest of the interpreter session. If an
767interpreter is started with the \programopt{-i} option, is passed a
768script name to execute, and the script includes a future statement, it
769will be in effect in the interactive session started after the script
770is executed.
Fred Drake2829f1c2001-06-23 05:27:20 +0000771
Fred Drake011f6fc1999-04-14 12:52:14 +0000772\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000773\stindex{global}
774
Fred Drakecb4638a2001-07-06 22:49:53 +0000775\begin{productionlist}
776 \production{global_stmt}
777 {"global" \token{identifier} ("," \token{identifier})*}
778\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000779
780The \keyword{global} statement is a declaration which holds for the
781entire current code block. It means that the listed identifiers are to be
Jeremy Hyltonf3255c82002-04-01 21:25:32 +0000782interpreted as globals. It would be impossible to assign to a global
783variable without \keyword{global}, although free variables may refer
784to globals without being declared global.
Fred Drakef6669171998-05-06 19:52:49 +0000785\indexiii{global}{name}{binding}
786
787Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000788code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000789
790Names listed in a \keyword{global} statement must not be defined as formal
791parameters or in a \keyword{for} loop control target, \keyword{class}
792definition, function definition, or \keyword{import} statement.
793
794(The current implementation does not enforce the latter two
795restrictions, but programs should not abuse this freedom, as future
796implementations may enforce them or silently change the meaning of the
797program.)
798
Guido van Rossum56c20131998-07-24 18:25:38 +0000799\strong{Programmer's note:}
800the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000801applies only to code parsed at the same time as the \keyword{global}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000802statement. In particular, a \keyword{global} statement contained in a
803string or code object supplied to the builtin \function{exec()} function
804does not affect the code block \emph{containing} the function call,
805and code contained in such a string is unaffected by \keyword{global}
806statements in the code containing the function call. The same applies to the
Fred Drakef6669171998-05-06 19:52:49 +0000807\function{eval()}, \function{execfile()} and \function{compile()} functions.
Georg Brandl7cae87c2006-09-06 06:51:57 +0000808\bifuncindex{exec}
Fred Drakef6669171998-05-06 19:52:49 +0000809\bifuncindex{eval}
810\bifuncindex{execfile}
811\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000812