blob: 122f499206728c287a0cca47a37620bf5a8c92aa [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}
9 \production{simple_stmt}
10 {\token{expression_stmt}
11 | \token{assert_stmt}
12 | \token{assignment_stmt}
13 | \token{augmented_assignment_stmt}
14 | \token{pass_stmt}
15 | \token{del_stmt}
16 | \token{print_stmt}
17 | \token{return_stmt}
Fred Drakee31e9ce2001-12-11 21:10:08 +000018 | \token{yield_stmt}
Fred Drakecb4638a2001-07-06 22:49:53 +000019 | \token{raise_stmt}
20 | \token{break_stmt}
21 | \token{continue_stmt}
22 | \token{import_stmt}
23 | \token{global_stmt}
24 | \token{exec_stmt}}
25\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000026
Fred Drake2829f1c2001-06-23 05:27:20 +000027
Fred Drake011f6fc1999-04-14 12:52:14 +000028\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000029\indexii{expression}{statement}
30
31Expression statements are used (mostly interactively) to compute and
32write a value, or (usually) to call a procedure (a function that
33returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000034\code{None}). Other uses of expression statements are allowed and
35occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000036
Fred Drakecb4638a2001-07-06 22:49:53 +000037\begin{productionlist}
38 \production{expression_stmt}
39 {\token{expression_list}}
40\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000041
Guido van Rossum56c20131998-07-24 18:25:38 +000042An expression statement evaluates the expression list (which may be a
43single expression).
Fred Drakef6669171998-05-06 19:52:49 +000044\indexii{expression}{list}
45
46In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000047to a string using the built-in \function{repr()}\bifuncindex{repr}
48function and the resulting string is written to standard output (see
Fred Drakec2f496a2001-12-05 05:46:25 +000049section~\ref{print}) on a line by itself. (Expression statements
50yielding \code{None} are not written, so that procedure calls do not
51cause any output.)
Fred Drakef6669171998-05-06 19:52:49 +000052\ttindex{None}
53\indexii{string}{conversion}
54\index{output}
55\indexii{standard}{output}
56\indexii{writing}{values}
57\indexii{procedure}{call}
58
Fred Drake2829f1c2001-06-23 05:27:20 +000059
Fred Drake011f6fc1999-04-14 12:52:14 +000060\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000061
Fred Drake011f6fc1999-04-14 12:52:14 +000062Assert statements\stindex{assert} are a convenient way to insert
63debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000064
Fred Drakecb4638a2001-07-06 22:49:53 +000065\begin{productionlist}
66 \production{assert_statement}
67 {"assert" \token{expression} ["," \token{expression}]}
68\end{productionlist}
Guido van Rossum56c20131998-07-24 18:25:38 +000069
Fred Drake011f6fc1999-04-14 12:52:14 +000070The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000071
72\begin{verbatim}
73if __debug__:
74 if not expression: raise AssertionError
75\end{verbatim}
76
Fred Drake011f6fc1999-04-14 12:52:14 +000077The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000078equivalent to
79
80\begin{verbatim}
81if __debug__:
82 if not expression1: raise AssertionError, expression2
83\end{verbatim}
84
85These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000086\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000087variables with those names. In the current implementation, the
88built-in variable \code{__debug__} is 1 under normal circumstances, 0
89when optimization is requested (command line option -O). The current
90code generator emits no code for an assert statement when optimization
91is requested at compile time. Note that it is unnecessary to include
92the source code for the expression that failed in the error message;
93it will be displayed as part of the stack trace.
94
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000095Assignments to \code{__debug__} are illegal. The value for the
96built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000097
Fred Drake2829f1c2001-06-23 05:27:20 +000098
Fred Drake011f6fc1999-04-14 12:52:14 +000099\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +0000100
Fred Drake011f6fc1999-04-14 12:52:14 +0000101Assignment statements\indexii{assignment}{statement} are used to
102(re)bind names to values and to modify attributes or items of mutable
103objects:
Fred Drakef6669171998-05-06 19:52:49 +0000104\indexii{binding}{name}
105\indexii{rebinding}{name}
106\obindex{mutable}
107\indexii{attribute}{assignment}
108
Fred Drakecb4638a2001-07-06 22:49:53 +0000109\begin{productionlist}
110 \production{assignment_stmt}
111 {(\token{target_list} "=")+ \token{expression_list}}
112 \production{target_list}
113 {\token{target} ("," \token{target})* [","]}
114 \production{target}
115 {\token{identifier}
116 | "(" \token{target_list} ")"
117 | "[" \token{target_list} "]"
118 | \token{attributeref}
119 | \token{subscription}
120 | \token{slicing}}
121\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000122
Fred Drakec2f496a2001-12-05 05:46:25 +0000123(See section~\ref{primaries} for the syntax definitions for the last
Fred Drakef6669171998-05-06 19:52:49 +0000124three symbols.)
125
126An assignment statement evaluates the expression list (remember that
127this can be a single expression or a comma-separated list, the latter
128yielding a tuple) and assigns the single resulting object to each of
129the target lists, from left to right.
130\indexii{expression}{list}
131
132Assignment is defined recursively depending on the form of the target
133(list). When a target is part of a mutable object (an attribute
134reference, subscription or slicing), the mutable object must
135ultimately perform the assignment and decide about its validity, and
136may raise an exception if the assignment is unacceptable. The rules
137observed by various types and the exceptions raised are given with the
Fred Drakec2f496a2001-12-05 05:46:25 +0000138definition of the object types (see section~\ref{types}).
Fred Drakef6669171998-05-06 19:52:49 +0000139\index{target}
140\indexii{target}{list}
141
142Assignment of an object to a target list is recursively defined as
143follows.
144\indexiii{target}{list}{assignment}
145
146\begin{itemize}
147\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000148If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000149target.
150
151\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000152If the target list is a comma-separated list of targets: The object
153must be a sequence with the same number of items as the there are
154targets in the target list, and the items are assigned, from left to
155right, to the corresponding targets. (This rule is relaxed as of
156Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000157strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000158now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000159
160\end{itemize}
161
162Assignment of an object to a single target is recursively defined as
163follows.
164
165\begin{itemize} % nested
166
167\item
168If the target is an identifier (name):
169
170\begin{itemize}
171
172\item
173If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000174code block: the name is bound to the object in the current local
175namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000176\stindex{global}
177
178\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000179Otherwise: the name is bound to the object in the current global
180namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000181
182\end{itemize} % nested
183
Guido van Rossum56c20131998-07-24 18:25:38 +0000184The name is rebound if it was already bound. This may cause the
185reference count for the object previously bound to the name to reach
186zero, causing the object to be deallocated and its
187destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000188
189\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000190If the target is a target list enclosed in parentheses or in square
191brackets: The object must be a sequence with the same number of items
192as there are targets in the target list, and its items are assigned,
193from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000194
195\item
196If the target is an attribute reference: The primary expression in the
197reference is evaluated. It should yield an object with assignable
198attributes; if this is not the case, \exception{TypeError} is raised. That
199object is then asked to assign the assigned object to the given
200attribute; if it cannot perform the assignment, it raises an exception
201(usually but not necessarily \exception{AttributeError}).
202\indexii{attribute}{assignment}
203
204\item
205If the target is a subscription: The primary expression in the
206reference is evaluated. It should yield either a mutable sequence
Guido van Rossum56c20131998-07-24 18:25:38 +0000207object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
208the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000209\indexii{subscription}{assignment}
210\obindex{mutable}
211
Guido van Rossum56c20131998-07-24 18:25:38 +0000212If the primary is a mutable sequence object (e.g., a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000213must yield a plain integer. If it is negative, the sequence's length
214is added to it. The resulting value must be a nonnegative integer
215less than the sequence's length, and the sequence is asked to assign
216the assigned object to its item with that index. If the index is out
217of range, \exception{IndexError} is raised (assignment to a subscripted
218sequence cannot add new items to a list).
219\obindex{sequence}
220\obindex{list}
221
Guido van Rossum56c20131998-07-24 18:25:38 +0000222If the primary is a mapping object (e.g., a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000223have a type compatible with the mapping's key type, and the mapping is
224then asked to create a key/datum pair which maps the subscript to
225the assigned object. This can either replace an existing key/value
226pair with the same key value, or insert a new key/value pair (if no
227key with the same value existed).
228\obindex{mapping}
229\obindex{dictionary}
230
231\item
232If the target is a slicing: The primary expression in the reference is
Guido van Rossum56c20131998-07-24 18:25:38 +0000233evaluated. It should yield a mutable sequence object (e.g., a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000234assigned object should be a sequence object of the same type. Next,
235the lower and upper bound expressions are evaluated, insofar they are
236present; defaults are zero and the sequence's length. The bounds
237should evaluate to (small) integers. If either bound is negative, the
238sequence's length is added to it. The resulting bounds are clipped to
239lie between zero and the sequence's length, inclusive. Finally, the
240sequence object is asked to replace the slice with the items of the
241assigned sequence. The length of the slice may be different from the
242length of the assigned sequence, thus changing the length of the
243target sequence, if the object allows it.
244\indexii{slicing}{assignment}
245
246\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000247
Fred Drakef6669171998-05-06 19:52:49 +0000248(In the current implementation, the syntax for targets is taken
249to be the same as for expressions, and invalid syntax is rejected
250during the code generation phase, causing less detailed error
251messages.)
252
253WARNING: Although the definition of assignment implies that overlaps
Guido van Rossum56c20131998-07-24 18:25:38 +0000254between the left-hand side and the right-hand side are `safe' (e.g.,
Fred Drake011f6fc1999-04-14 12:52:14 +0000255\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000256collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000257following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000258
259\begin{verbatim}
260x = [0, 1]
261i = 0
262i, x[i] = 1, 2
263print x
264\end{verbatim}
265
266
Fred Drake31f55502000-09-12 20:32:18 +0000267\subsection{Augmented Assignment statements \label{augassign}}
268
269Augmented assignment is the combination, in a single statement, of a binary
270operation and an assignment statement:
271\indexii{augmented}{assignment}
272\index{statement!assignment, augmented}
273
Fred Drakecb4638a2001-07-06 22:49:53 +0000274\begin{productionlist}
275 \production{augmented_assignment_stmt}
276 {\token{target} \token{augop} \token{expression_list}}
277 \production{augop}
278 {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="
279 | ">>=" | "<<=" | "\&=" | "\textasciicircum=" | "|="}
280 \production{target}
281 {\token{identifier}
282 | "(" \token{target_list} ")"
283 | "[" \token{target_list} "]"
284 | \token{attributeref}
285 | \token{subscription}
286 | \token{slicing}}
287\end{productionlist}
Fred Drake31f55502000-09-12 20:32:18 +0000288
Fred Drakec2f496a2001-12-05 05:46:25 +0000289(See section~\ref{primaries} for the syntax definitions for the last
Fred Drake31f55502000-09-12 20:32:18 +0000290three symbols.)
291
Fred Draked68442b2000-09-21 22:01:36 +0000292An augmented assignment evaluates the target (which, unlike normal
293assignment statements, cannot be an unpacking) and the expression
294list, performs the binary operation specific to the type of assignment
295on the two operands, and assigns the result to the original
296target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000297
298An augmented assignment expression like \code{x += 1} can be rewritten as
299\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
300augmented version, \code{x} is only evaluated once. Also, when possible, the
301actual operation is performed \emph{in-place}, meaning that rather than
302creating a new object and assigning that to the target, the old object is
303modified instead.
304
305With the exception of assigning to tuples and multiple targets in a single
306statement, the assignment done by augmented assignment statements is handled
307the same way as normal assignments. Similarly, with the exception of the
Fred Drakec2f496a2001-12-05 05:46:25 +0000308possible \emph{in-place} behavior, the binary operation performed by
Fred Drake31f55502000-09-12 20:32:18 +0000309augmented assignment is the same as the normal binary operations.
310
311
Fred Drake011f6fc1999-04-14 12:52:14 +0000312\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000313\stindex{pass}
314
Fred Drakecb4638a2001-07-06 22:49:53 +0000315\begin{productionlist}
316 \production{pass_stmt}
317 {"pass"}
318\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000319
320\keyword{pass} is a null operation --- when it is executed, nothing
321happens. It is useful as a placeholder when a statement is
322required syntactically, but no code needs to be executed, for example:
323\indexii{null}{operation}
324
325\begin{verbatim}
326def f(arg): pass # a function that does nothing (yet)
327
328class C: pass # a class with no methods (yet)
329\end{verbatim}
330
Fred Drake2829f1c2001-06-23 05:27:20 +0000331
Fred Drake011f6fc1999-04-14 12:52:14 +0000332\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000333\stindex{del}
334
Fred Drakecb4638a2001-07-06 22:49:53 +0000335\begin{productionlist}
336 \production{del_stmt}
337 {"del" \token{target_list}}
338\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000339
340Deletion is recursively defined very similar to the way assignment is
341defined. Rather that spelling it out in full details, here are some
342hints.
343\indexii{deletion}{target}
344\indexiii{deletion}{target}{list}
345
346Deletion of a target list recursively deletes each target, from left
347to right.
348
349Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum56c20131998-07-24 18:25:38 +0000350from the local or global namespace, depending on whether the name
Fred Drakef6669171998-05-06 19:52:49 +0000351occurs in a \keyword{global} statement in the same code block.
352\stindex{global}
353\indexii{unbinding}{name}
354
355Deletion of attribute references, subscriptions and slicings
356is passed to the primary object involved; deletion of a slicing
357is in general equivalent to assignment of an empty slice of the
358right type (but even this is determined by the sliced object).
359\indexii{attribute}{deletion}
360
Fred Drake2829f1c2001-06-23 05:27:20 +0000361
Fred Drake011f6fc1999-04-14 12:52:14 +0000362\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000363\stindex{print}
364
Fred Drakecb4638a2001-07-06 22:49:53 +0000365\begin{productionlist}
366 \production{print_stmt}
367 {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}
368 | ">\code{>}" \token{expression}
369 \optional{("," \token{expression})+ \optional{","}})}
370\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000371
Fred Draked4c33521998-10-01 20:39:47 +0000372\keyword{print} evaluates each expression in turn and writes the
373resulting object to standard output (see below). If an object is not
Fred Drakebe9d10e2001-06-23 06:16:52 +0000374a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000375conversions. The (resulting or original) string is then written. A
Fred Drakebe9d10e2001-06-23 06:16:52 +0000376space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000377the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000378line. This is the case (1) when no characters have yet been written
379to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000380output is \character{\e n}, or (3) when the last write operation on
381standard output was not a \keyword{print} statement. (In some cases
382it may be functional to write an empty string to standard output for
Fred Drakec2f496a2001-12-05 05:46:25 +0000383this reason.) \note{Objects which act like file objects but which are
384not the built-in file objects often do not properly emulate this
385aspect of the file object's behavior, so it is best not to rely on
386this.}
Fred Drakef6669171998-05-06 19:52:49 +0000387\index{output}
388\indexii{writing}{values}
389
Fred Draked4c33521998-10-01 20:39:47 +0000390A \character{\e n} character is written at the end, unless the
391\keyword{print} statement ends with a comma. This is the only action
392if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000393\indexii{trailing}{comma}
394\indexii{newline}{suppression}
395
Fred Drakedde91f01998-05-06 20:59:46 +0000396Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000397in the built-in module \module{sys}. If no such object exists, or if
398it does not have a \method{write()} method, a \exception{RuntimeError}
399exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000400\indexii{standard}{output}
401\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000402\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000403\exindex{RuntimeError}
404
Fred Drakecb4638a2001-07-06 22:49:53 +0000405\keyword{print} also has an extended\index{extended print statement}
406form, defined by the second portion of the syntax described above.
407This form is sometimes referred to as ``\keyword{print} chevron.''
Fred Drake62effc12001-04-13 15:55:25 +0000408In this form, the first expression after the \code{>}\code{>} must
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000409evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000410\method{write()} method as described above. With this extended form,
411the subsequent expressions are printed to this file object. If the
412first expression evaluates to \code{None}, then \code{sys.stdout} is
413used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000414
Fred Drake2829f1c2001-06-23 05:27:20 +0000415
Fred Drake011f6fc1999-04-14 12:52:14 +0000416\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000417\stindex{return}
418
Fred Drakecb4638a2001-07-06 22:49:53 +0000419\begin{productionlist}
420 \production{return_stmt}
421 {"return" [\token{expression_list}]}
422\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000423
424\keyword{return} may only occur syntactically nested in a function
425definition, not within a nested class definition.
426\indexii{function}{definition}
427\indexii{class}{definition}
428
Guido van Rossum56c20131998-07-24 18:25:38 +0000429If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000430is substituted.
431
Guido van Rossum56c20131998-07-24 18:25:38 +0000432\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000433list (or \code{None}) as return value.
434
435When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000436with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000437before really leaving the function.
438\kwindex{finally}
439
Fred Drakee31e9ce2001-12-11 21:10:08 +0000440In a generator function, the \keyword{return} statement is not allowed
441to include an \grammartoken{expression_list}. In that context, a bare
442\keyword{return} indicates that the generator is done and will cause
443\exception{StopIteration} to be raised.
444
445
446\section{The \keyword{yield} statement \label{yield}}
447\stindex{yield}
448
449\begin{productionlist}
450 \production{yield_stmt}
451 {"yield" \token{expression_list}}
452\end{productionlist}
453
454\index{generator!function}
455\index{generator!iterator}
456\index{function!generator}
457\exindex{StopIteration}
458
459The \keyword{yield} statement is only used when defining a generator
460function, and is only used in the body of the generator function.
461Using a \keyword{yield} statement in a function definition is
462sufficient to cause that definition to create a generator function
463instead of a normal function.
464
465When a generator function is called, it returns an iterator known as a
466generator iterator, or more commonly, a generator. The body of the
467generator function is executed by calling the generator's
468\method{next()} method repeatedly until it raises an exception.
469
470When a \keyword{yield} statement is executed, the state of the
471generator is frozen and the value of \grammartoken{expression_list} is
472returned to \method{next()}'s caller. By ``frozen'' we mean that all
473local state is retained, including the current bindings of local
474variables, the instruction pointer, and the internal evaluation stack:
475enough information is saved so that the next time \method{next()} is
476invoked, the function can proceed exactly as if the \keyword{yield}
477statement were just another external call.
478
Fred Drake3a8e59e2001-12-11 21:58:35 +0000479The \keyword{yield} statement is not allowed in the \keyword{try}
480clause of a \keyword{try} ...\ \keyword{finally} construct. The
481difficulty is that there's no guarantee the generator will ever be
482resumed, hence no guarantee that the \keyword{finally} block will ever
483get executed.
Fred Drakee31e9ce2001-12-11 21:10:08 +0000484
Fred Drake08d752c2001-12-14 22:55:14 +0000485\begin{notice}
486In Python 2.2, the \keyword{yield} statement is only allowed
Fred Drake8d0645c2001-12-12 06:06:43 +0000487when the \code{generators} feature has been enabled. It will always
488be enabled in Python 2.3. This \code{__future__} import statment can
Fred Drake08d752c2001-12-14 22:55:14 +0000489be used to enable the feature:
Fred Drake8d0645c2001-12-12 06:06:43 +0000490
491\begin{verbatim}
492from __future__ import generators
493\end{verbatim}
Fred Drake08d752c2001-12-14 22:55:14 +0000494\end{notice}
Fred Drake8d0645c2001-12-12 06:06:43 +0000495
496
Fred Drakee31e9ce2001-12-11 21:10:08 +0000497\begin{seealso}
498 \seepep{0255}{Simple Generators}
499 {The proposal for adding generators and the \keyword{yield}
500 statement to Python.}
501\end{seealso}
502
Fred Drake2829f1c2001-06-23 05:27:20 +0000503
Fred Drake011f6fc1999-04-14 12:52:14 +0000504\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000505\stindex{raise}
506
Fred Drakecb4638a2001-07-06 22:49:53 +0000507\begin{productionlist}
508 \production{raise_stmt}
509 {"raise" [\token{expression} ["," \token{expression}
510 ["," \token{expression}]]]}
511\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000512
Guido van Rossum56c20131998-07-24 18:25:38 +0000513If no expressions are present, \keyword{raise} re-raises the last
514expression that was raised in the current scope.
515
Fred Drake011f6fc1999-04-14 12:52:14 +0000516Otherwise, \keyword{raise} evaluates its first expression, which must yield
Guido van Rossum56c20131998-07-24 18:25:38 +0000517a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000518this is evaluated, else \code{None} is substituted. If the first
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000519expression is a class object, then the second expression may be an
520instance of that class or one of its derivatives, and then that
521instance is raised. If the second expression is not such an instance,
522the given class is instantiated. The argument list for the
523instantiation is determined as follows: if the second expression is a
524tuple, it is used as the argument list; if it is \code{None}, the
525argument list is empty; otherwise, the argument list consists of a
526single argument which is the second expression. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000527expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000528\code{None}.
529\index{exception}
530\indexii{raising}{exception}
531
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000532If the first object is a string, it then raises the exception
Fred Drakef6669171998-05-06 19:52:49 +0000533identified by the first object, with the second one (or \code{None})
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000534as its parameter. If the first object is a class or instance,
535it raises the exception identified by the class of the instance
536determined in the previous step, with the instance as
537its parameter.
Fred Drakef6669171998-05-06 19:52:49 +0000538
Guido van Rossum56c20131998-07-24 18:25:38 +0000539If a third object is present, and it is not \code{None}, it should be
Fred Drakec2f496a2001-12-05 05:46:25 +0000540a traceback object (see section~\ref{traceback}), and it is
Fred Drakef6669171998-05-06 19:52:49 +0000541substituted instead of the current location as the place where the
542exception occurred. This is useful to re-raise an exception
543transparently in an except clause.
544\obindex{traceback}
545
Fred Drake2829f1c2001-06-23 05:27:20 +0000546
Fred Drake011f6fc1999-04-14 12:52:14 +0000547\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000548\stindex{break}
549
Fred Drakecb4638a2001-07-06 22:49:53 +0000550\begin{productionlist}
551 \production{break_stmt}
552 {"break"}
553\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000554
555\keyword{break} may only occur syntactically nested in a \keyword{for}
556or \keyword{while} loop, but not nested in a function or class definition
557within that loop.
558\stindex{for}
559\stindex{while}
560\indexii{loop}{statement}
561
562It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000563\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000564\kwindex{else}
565
566If a \keyword{for} loop is terminated by \keyword{break}, the loop control
567target keeps its current value.
568\indexii{loop control}{target}
569
570When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000571with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000572before really leaving the loop.
573\kwindex{finally}
574
Fred Drake2829f1c2001-06-23 05:27:20 +0000575
Fred Drake011f6fc1999-04-14 12:52:14 +0000576\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000577\stindex{continue}
578
Fred Drakecb4638a2001-07-06 22:49:53 +0000579\begin{productionlist}
580 \production{continue_stmt}
581 {"continue"}
582\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000583
584\keyword{continue} may only occur syntactically nested in a \keyword{for} or
585\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000586\keyword{try} statement within that loop.\footnote{It may
587occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000588restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000589laziness and will eventually be lifted.}
590It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000591\stindex{for}
592\stindex{while}
593\indexii{loop}{statement}
594\kwindex{finally}
595
Fred Drake2829f1c2001-06-23 05:27:20 +0000596
Fred Drake011f6fc1999-04-14 12:52:14 +0000597\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000598\stindex{import}
599
Fred Drakecb4638a2001-07-06 22:49:53 +0000600\begin{productionlist}
601 \production{import_stmt}
602 {"import" \token{module} ["as" \token{name}]
603 ( "," \token{module} ["as" \token{name}] )*
604 | "from" \token{module} "import" \token{identifier}
605 ["as" \token{name}]
606 ( "," \token{identifier} ["as" \token{name}] )*
607 | "from" \token{module} "import" "*"}
608 \production{module}
609 {(\token{identifier} ".")* \token{identifier}}
610\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000611
612Import statements are executed in two steps: (1) find a module, and
613initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000614namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000615The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000616identifier in the list. The form with \keyword{from} performs step
617(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000618\indexii{importing}{module}
619\indexii{name}{binding}
620\kwindex{from}
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000621% XXX Need to define what ``initialize'' means here
Fred Drakef6669171998-05-06 19:52:49 +0000622
623The system maintains a table of modules that have been initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000624indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000625accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000626this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000627definition is started. When a module is found, it is loaded. Details
628of the module searching and loading process are implementation and
629platform specific. It generally involves searching for a ``built-in''
630module with the given name and then searching a list of locations
631given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000632\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000633\ttindex{sys.modules}
634\indexii{module}{name}
635\indexii{built-in}{module}
636\indexii{user-defined}{module}
637\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000638\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000639\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000640
641If a built-in module is found, its built-in initialization code is
642executed and step (1) is finished. If no matching file is found,
643\exception{ImportError} is raised. If a file is found, it is parsed,
644yielding an executable code block. If a syntax error occurs,
645\exception{SyntaxError} is raised. Otherwise, an empty module of the given
646name is created and inserted in the module table, and then the code
647block is executed in the context of this module. Exceptions during
648this execution terminate step (1).
649\indexii{module}{initialization}
650\exindex{SyntaxError}
651\exindex{ImportError}
652\index{code block}
653
654When step (1) finishes without raising an exception, step (2) can
655begin.
656
Fred Drake859eb622001-03-06 07:34:00 +0000657The first form of \keyword{import} statement binds the module name in
658the local namespace to the module object, and then goes on to import
659the next identifier, if any. If the module name is followed by
660\keyword{as}, the name following \keyword{as} is used as the local
661name for the module. To avoid confusion, you cannot import modules
662with dotted names \keyword{as} a different local name. So \code{import
663module as m} is legal, but \code{import module.submod as s} is not.
664The latter should be written as \code{from module import submod as s};
Thomas Wouters8bad6122000-08-19 20:55:02 +0000665see below.
666
Thomas Wouters52152252000-08-17 22:55:00 +0000667The \keyword{from} form does not bind the module name: it goes through the
668list of identifiers, looks each one of them up in the module found in step
669(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000670As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000671supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000672\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drake08fd5152001-10-24 19:50:31 +0000673by a star (\character{*}), all public names defined in the module are
674bound in the local namespace of the \keyword{import} statement..
Fred Drakef6669171998-05-06 19:52:49 +0000675\indexii{name}{binding}
676\exindex{ImportError}
677
Fred Drake08fd5152001-10-24 19:50:31 +0000678The \emph{public names} defined by a module are determined by checking
679the module's namespace for a variable named \code{__all__}; if
680defined, it must be a sequence of strings which are names defined or
681imported by that module. The names given in \code{__all__} are all
682considered public and are required to exist. If \code{__all__} is not
683defined, the set of public names includes all names found in the
684module's namespace which do not begin with an underscore character
685(\character{_}).
686
Guido van Rossum56c20131998-07-24 18:25:38 +0000687Names bound by \keyword{import} statements may not occur in
688\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000689\stindex{global}
690
Fred Drake011f6fc1999-04-14 12:52:14 +0000691The \keyword{from} form with \samp{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000692\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000693\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000694
Fred Drake246837d1998-07-24 20:28:22 +0000695\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000696when the module names contains one or more dots, the module search
697path is carried out differently. The sequence of identifiers up to
698the last dot is used to find a ``package''\index{packages}; the final
699identifier is then searched inside the package. A package is
700generally a subdirectory of a directory on \code{sys.path} that has a
701file \file{__init__.py}.\ttindex{__init__.py}
702%
703[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000704\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000705about how the module search works from inside a package.]
706
Fred Drake08fd5152001-10-24 19:50:31 +0000707The built-in function \function{__import__()} is provided to support
708applications that determine which modules need to be loaded
709dynamically; refer to \ulink{Built-in
710Functions}{../lib/built-in-funcs.html} in the
711\citetitle[../lib/lib.html]{Python Library Reference} for additional
712information.
Guido van Rossum56c20131998-07-24 18:25:38 +0000713\bifuncindex{__import__}
714
Fred Drake2829f1c2001-06-23 05:27:20 +0000715
Fred Drake011f6fc1999-04-14 12:52:14 +0000716\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000717\stindex{global}
718
Fred Drakecb4638a2001-07-06 22:49:53 +0000719\begin{productionlist}
720 \production{global_stmt}
721 {"global" \token{identifier} ("," \token{identifier})*}
722\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000723
724The \keyword{global} statement is a declaration which holds for the
725entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000726interpreted as globals. While \emph{using} global names is automatic
727if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000728names would be impossible without \keyword{global}.
729\indexiii{global}{name}{binding}
730
731Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000732code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000733
734Names listed in a \keyword{global} statement must not be defined as formal
735parameters or in a \keyword{for} loop control target, \keyword{class}
736definition, function definition, or \keyword{import} statement.
737
738(The current implementation does not enforce the latter two
739restrictions, but programs should not abuse this freedom, as future
740implementations may enforce them or silently change the meaning of the
741program.)
742
Guido van Rossum56c20131998-07-24 18:25:38 +0000743\strong{Programmer's note:}
744the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000745applies only to code parsed at the same time as the \keyword{global}
746statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000747\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000748the \keyword{exec} statement, and code contained in an \keyword{exec}
749statement is unaffected by \keyword{global} statements in the code
750containing the \keyword{exec} statement. The same applies to the
751\function{eval()}, \function{execfile()} and \function{compile()} functions.
752\stindex{exec}
753\bifuncindex{eval}
754\bifuncindex{execfile}
755\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000756
Fred Drake2829f1c2001-06-23 05:27:20 +0000757
Fred Drake011f6fc1999-04-14 12:52:14 +0000758\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000759\stindex{exec}
760
Fred Drakecb4638a2001-07-06 22:49:53 +0000761\begin{productionlist}
762 \production{exec_stmt}
763 {"exec" \token{expression}
764 ["in" \token{expression} ["," \token{expression}]]}
765\end{productionlist}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000766
767This statement supports dynamic execution of Python code. The first
768expression should evaluate to either a string, an open file object, or
769a code object. If it is a string, the string is parsed as a suite of
770Python statements which is then executed (unless a syntax error
Fred Drake93852ef2001-06-23 06:06:52 +0000771occurs). If it is an open file, the file is parsed until \EOF{} and
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000772executed. If it is a code object, it is simply executed.
773
774In all cases, if the optional parts are omitted, the code is executed
775in the current scope. If only the first expression after \keyword{in}
776is specified, it should be a dictionary, which will be used for both
777the global and the local variables. If two expressions are given,
778both must be dictionaries and they are used for the global and local
779variables, respectively.
780
781As a side effect, an implementation may insert additional keys into
782the dictionaries given besides those corresponding to variable names
783set by the executed code. For example, the current implementation
784may add a reference to the dictionary of the built-in module
785\module{__builtin__} under the key \code{__builtins__} (!).
786\ttindex{__builtins__}
787\refbimodindex{__builtin__}
788
Guido van Rossum56c20131998-07-24 18:25:38 +0000789\strong{Programmer's hints:}
790dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000791function \function{eval()}. The built-in functions
792\function{globals()} and \function{locals()} return the current global
793and local dictionary, respectively, which may be useful to pass around
794for use by \keyword{exec}.
795\bifuncindex{eval}
796\bifuncindex{globals}
797\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000798
799Also, in the current implementation, multi-line compound statements must
800end with a newline:
801\code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
802\code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
803\exception{SyntaxError}.
804\exindex{SyntaxError}
805
806