blob: 3089b1af387eb7d1fdae5d3299b15c1cd31c6cda [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 Drake8d0645c2001-12-12 06:06:43 +0000485\note{In Python 2.2, the \keyword{yield} statement is only allowed
486when the \code{generators} feature has been enabled. It will always
487be enabled in Python 2.3. This \code{__future__} import statment can
488be used to enable the feature:}
489
490\begin{verbatim}
491from __future__ import generators
492\end{verbatim}
493
494
Fred Drakee31e9ce2001-12-11 21:10:08 +0000495\begin{seealso}
496 \seepep{0255}{Simple Generators}
497 {The proposal for adding generators and the \keyword{yield}
498 statement to Python.}
499\end{seealso}
500
Fred Drake2829f1c2001-06-23 05:27:20 +0000501
Fred Drake011f6fc1999-04-14 12:52:14 +0000502\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000503\stindex{raise}
504
Fred Drakecb4638a2001-07-06 22:49:53 +0000505\begin{productionlist}
506 \production{raise_stmt}
507 {"raise" [\token{expression} ["," \token{expression}
508 ["," \token{expression}]]]}
509\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000510
Guido van Rossum56c20131998-07-24 18:25:38 +0000511If no expressions are present, \keyword{raise} re-raises the last
512expression that was raised in the current scope.
513
Fred Drake011f6fc1999-04-14 12:52:14 +0000514Otherwise, \keyword{raise} evaluates its first expression, which must yield
Guido van Rossum56c20131998-07-24 18:25:38 +0000515a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000516this is evaluated, else \code{None} is substituted. If the first
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000517expression is a class object, then the second expression may be an
518instance of that class or one of its derivatives, and then that
519instance is raised. If the second expression is not such an instance,
520the given class is instantiated. The argument list for the
521instantiation is determined as follows: if the second expression is a
522tuple, it is used as the argument list; if it is \code{None}, the
523argument list is empty; otherwise, the argument list consists of a
524single argument which is the second expression. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000525expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000526\code{None}.
527\index{exception}
528\indexii{raising}{exception}
529
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000530If the first object is a string, it then raises the exception
Fred Drakef6669171998-05-06 19:52:49 +0000531identified by the first object, with the second one (or \code{None})
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000532as its parameter. If the first object is a class or instance,
533it raises the exception identified by the class of the instance
534determined in the previous step, with the instance as
535its parameter.
Fred Drakef6669171998-05-06 19:52:49 +0000536
Guido van Rossum56c20131998-07-24 18:25:38 +0000537If a third object is present, and it is not \code{None}, it should be
Fred Drakec2f496a2001-12-05 05:46:25 +0000538a traceback object (see section~\ref{traceback}), and it is
Fred Drakef6669171998-05-06 19:52:49 +0000539substituted instead of the current location as the place where the
540exception occurred. This is useful to re-raise an exception
541transparently in an except clause.
542\obindex{traceback}
543
Fred Drake2829f1c2001-06-23 05:27:20 +0000544
Fred Drake011f6fc1999-04-14 12:52:14 +0000545\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000546\stindex{break}
547
Fred Drakecb4638a2001-07-06 22:49:53 +0000548\begin{productionlist}
549 \production{break_stmt}
550 {"break"}
551\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000552
553\keyword{break} may only occur syntactically nested in a \keyword{for}
554or \keyword{while} loop, but not nested in a function or class definition
555within that loop.
556\stindex{for}
557\stindex{while}
558\indexii{loop}{statement}
559
560It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000561\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000562\kwindex{else}
563
564If a \keyword{for} loop is terminated by \keyword{break}, the loop control
565target keeps its current value.
566\indexii{loop control}{target}
567
568When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000569with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000570before really leaving the loop.
571\kwindex{finally}
572
Fred Drake2829f1c2001-06-23 05:27:20 +0000573
Fred Drake011f6fc1999-04-14 12:52:14 +0000574\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000575\stindex{continue}
576
Fred Drakecb4638a2001-07-06 22:49:53 +0000577\begin{productionlist}
578 \production{continue_stmt}
579 {"continue"}
580\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000581
582\keyword{continue} may only occur syntactically nested in a \keyword{for} or
583\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000584\keyword{try} statement within that loop.\footnote{It may
585occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000586restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000587laziness and will eventually be lifted.}
588It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000589\stindex{for}
590\stindex{while}
591\indexii{loop}{statement}
592\kwindex{finally}
593
Fred Drake2829f1c2001-06-23 05:27:20 +0000594
Fred Drake011f6fc1999-04-14 12:52:14 +0000595\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000596\stindex{import}
597
Fred Drakecb4638a2001-07-06 22:49:53 +0000598\begin{productionlist}
599 \production{import_stmt}
600 {"import" \token{module} ["as" \token{name}]
601 ( "," \token{module} ["as" \token{name}] )*
602 | "from" \token{module} "import" \token{identifier}
603 ["as" \token{name}]
604 ( "," \token{identifier} ["as" \token{name}] )*
605 | "from" \token{module} "import" "*"}
606 \production{module}
607 {(\token{identifier} ".")* \token{identifier}}
608\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000609
610Import statements are executed in two steps: (1) find a module, and
611initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000612namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000613The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000614identifier in the list. The form with \keyword{from} performs step
615(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000616\indexii{importing}{module}
617\indexii{name}{binding}
618\kwindex{from}
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000619% XXX Need to define what ``initialize'' means here
Fred Drakef6669171998-05-06 19:52:49 +0000620
621The system maintains a table of modules that have been initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000622indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000623accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000624this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000625definition is started. When a module is found, it is loaded. Details
626of the module searching and loading process are implementation and
627platform specific. It generally involves searching for a ``built-in''
628module with the given name and then searching a list of locations
629given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000630\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000631\ttindex{sys.modules}
632\indexii{module}{name}
633\indexii{built-in}{module}
634\indexii{user-defined}{module}
635\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000636\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000637\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000638
639If a built-in module is found, its built-in initialization code is
640executed and step (1) is finished. If no matching file is found,
641\exception{ImportError} is raised. If a file is found, it is parsed,
642yielding an executable code block. If a syntax error occurs,
643\exception{SyntaxError} is raised. Otherwise, an empty module of the given
644name is created and inserted in the module table, and then the code
645block is executed in the context of this module. Exceptions during
646this execution terminate step (1).
647\indexii{module}{initialization}
648\exindex{SyntaxError}
649\exindex{ImportError}
650\index{code block}
651
652When step (1) finishes without raising an exception, step (2) can
653begin.
654
Fred Drake859eb622001-03-06 07:34:00 +0000655The first form of \keyword{import} statement binds the module name in
656the local namespace to the module object, and then goes on to import
657the next identifier, if any. If the module name is followed by
658\keyword{as}, the name following \keyword{as} is used as the local
659name for the module. To avoid confusion, you cannot import modules
660with dotted names \keyword{as} a different local name. So \code{import
661module as m} is legal, but \code{import module.submod as s} is not.
662The latter should be written as \code{from module import submod as s};
Thomas Wouters8bad6122000-08-19 20:55:02 +0000663see below.
664
Thomas Wouters52152252000-08-17 22:55:00 +0000665The \keyword{from} form does not bind the module name: it goes through the
666list of identifiers, looks each one of them up in the module found in step
667(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000668As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000669supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000670\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drake08fd5152001-10-24 19:50:31 +0000671by a star (\character{*}), all public names defined in the module are
672bound in the local namespace of the \keyword{import} statement..
Fred Drakef6669171998-05-06 19:52:49 +0000673\indexii{name}{binding}
674\exindex{ImportError}
675
Fred Drake08fd5152001-10-24 19:50:31 +0000676The \emph{public names} defined by a module are determined by checking
677the module's namespace for a variable named \code{__all__}; if
678defined, it must be a sequence of strings which are names defined or
679imported by that module. The names given in \code{__all__} are all
680considered public and are required to exist. If \code{__all__} is not
681defined, the set of public names includes all names found in the
682module's namespace which do not begin with an underscore character
683(\character{_}).
684
Guido van Rossum56c20131998-07-24 18:25:38 +0000685Names bound by \keyword{import} statements may not occur in
686\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000687\stindex{global}
688
Fred Drake011f6fc1999-04-14 12:52:14 +0000689The \keyword{from} form with \samp{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000690\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000691\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000692
Fred Drake246837d1998-07-24 20:28:22 +0000693\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000694when the module names contains one or more dots, the module search
695path is carried out differently. The sequence of identifiers up to
696the last dot is used to find a ``package''\index{packages}; the final
697identifier is then searched inside the package. A package is
698generally a subdirectory of a directory on \code{sys.path} that has a
699file \file{__init__.py}.\ttindex{__init__.py}
700%
701[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000702\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000703about how the module search works from inside a package.]
704
Fred Drake08fd5152001-10-24 19:50:31 +0000705The built-in function \function{__import__()} is provided to support
706applications that determine which modules need to be loaded
707dynamically; refer to \ulink{Built-in
708Functions}{../lib/built-in-funcs.html} in the
709\citetitle[../lib/lib.html]{Python Library Reference} for additional
710information.
Guido van Rossum56c20131998-07-24 18:25:38 +0000711\bifuncindex{__import__}
712
Fred Drake2829f1c2001-06-23 05:27:20 +0000713
Fred Drake011f6fc1999-04-14 12:52:14 +0000714\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000715\stindex{global}
716
Fred Drakecb4638a2001-07-06 22:49:53 +0000717\begin{productionlist}
718 \production{global_stmt}
719 {"global" \token{identifier} ("," \token{identifier})*}
720\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000721
722The \keyword{global} statement is a declaration which holds for the
723entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000724interpreted as globals. While \emph{using} global names is automatic
725if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000726names would be impossible without \keyword{global}.
727\indexiii{global}{name}{binding}
728
729Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000730code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000731
732Names listed in a \keyword{global} statement must not be defined as formal
733parameters or in a \keyword{for} loop control target, \keyword{class}
734definition, function definition, or \keyword{import} statement.
735
736(The current implementation does not enforce the latter two
737restrictions, but programs should not abuse this freedom, as future
738implementations may enforce them or silently change the meaning of the
739program.)
740
Guido van Rossum56c20131998-07-24 18:25:38 +0000741\strong{Programmer's note:}
742the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000743applies only to code parsed at the same time as the \keyword{global}
744statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000745\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000746the \keyword{exec} statement, and code contained in an \keyword{exec}
747statement is unaffected by \keyword{global} statements in the code
748containing the \keyword{exec} statement. The same applies to the
749\function{eval()}, \function{execfile()} and \function{compile()} functions.
750\stindex{exec}
751\bifuncindex{eval}
752\bifuncindex{execfile}
753\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000754
Fred Drake2829f1c2001-06-23 05:27:20 +0000755
Fred Drake011f6fc1999-04-14 12:52:14 +0000756\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000757\stindex{exec}
758
Fred Drakecb4638a2001-07-06 22:49:53 +0000759\begin{productionlist}
760 \production{exec_stmt}
761 {"exec" \token{expression}
762 ["in" \token{expression} ["," \token{expression}]]}
763\end{productionlist}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000764
765This statement supports dynamic execution of Python code. The first
766expression should evaluate to either a string, an open file object, or
767a code object. If it is a string, the string is parsed as a suite of
768Python statements which is then executed (unless a syntax error
Fred Drake93852ef2001-06-23 06:06:52 +0000769occurs). If it is an open file, the file is parsed until \EOF{} and
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000770executed. If it is a code object, it is simply executed.
771
772In all cases, if the optional parts are omitted, the code is executed
773in the current scope. If only the first expression after \keyword{in}
774is specified, it should be a dictionary, which will be used for both
775the global and the local variables. If two expressions are given,
776both must be dictionaries and they are used for the global and local
777variables, respectively.
778
779As a side effect, an implementation may insert additional keys into
780the dictionaries given besides those corresponding to variable names
781set by the executed code. For example, the current implementation
782may add a reference to the dictionary of the built-in module
783\module{__builtin__} under the key \code{__builtins__} (!).
784\ttindex{__builtins__}
785\refbimodindex{__builtin__}
786
Guido van Rossum56c20131998-07-24 18:25:38 +0000787\strong{Programmer's hints:}
788dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000789function \function{eval()}. The built-in functions
790\function{globals()} and \function{locals()} return the current global
791and local dictionary, respectively, which may be useful to pass around
792for use by \keyword{exec}.
793\bifuncindex{eval}
794\bifuncindex{globals}
795\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000796
797Also, in the current implementation, multi-line compound statements must
798end with a newline:
799\code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
800\code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
801\exception{SyntaxError}.
802\exindex{SyntaxError}
803
804