blob: 8691cdfc617212bc6bd6a548798eecb5d0748bd3 [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}
18 | \token{raise_stmt}
19 | \token{break_stmt}
20 | \token{continue_stmt}
21 | \token{import_stmt}
22 | \token{global_stmt}
23 | \token{exec_stmt}}
24\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000025
Fred Drake2829f1c2001-06-23 05:27:20 +000026
Fred Drake011f6fc1999-04-14 12:52:14 +000027\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000028\indexii{expression}{statement}
29
30Expression statements are used (mostly interactively) to compute and
31write a value, or (usually) to call a procedure (a function that
32returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000033\code{None}). Other uses of expression statements are allowed and
34occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000035
Fred Drakecb4638a2001-07-06 22:49:53 +000036\begin{productionlist}
37 \production{expression_stmt}
38 {\token{expression_list}}
39\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000040
Guido van Rossum56c20131998-07-24 18:25:38 +000041An expression statement evaluates the expression list (which may be a
42single expression).
Fred Drakef6669171998-05-06 19:52:49 +000043\indexii{expression}{list}
44
45In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000046to a string using the built-in \function{repr()}\bifuncindex{repr}
47function and the resulting string is written to standard output (see
Fred Drakec2f496a2001-12-05 05:46:25 +000048section~\ref{print}) on a line by itself. (Expression statements
49yielding \code{None} are not written, so that procedure calls do not
50cause any output.)
Fred Drakef6669171998-05-06 19:52:49 +000051\ttindex{None}
52\indexii{string}{conversion}
53\index{output}
54\indexii{standard}{output}
55\indexii{writing}{values}
56\indexii{procedure}{call}
57
Fred Drake2829f1c2001-06-23 05:27:20 +000058
Fred Drake011f6fc1999-04-14 12:52:14 +000059\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000060
Fred Drake011f6fc1999-04-14 12:52:14 +000061Assert statements\stindex{assert} are a convenient way to insert
62debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000063
Fred Drakecb4638a2001-07-06 22:49:53 +000064\begin{productionlist}
65 \production{assert_statement}
66 {"assert" \token{expression} ["," \token{expression}]}
67\end{productionlist}
Guido van Rossum56c20131998-07-24 18:25:38 +000068
Fred Drake011f6fc1999-04-14 12:52:14 +000069The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000070
71\begin{verbatim}
72if __debug__:
73 if not expression: raise AssertionError
74\end{verbatim}
75
Fred Drake011f6fc1999-04-14 12:52:14 +000076The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000077equivalent to
78
79\begin{verbatim}
80if __debug__:
81 if not expression1: raise AssertionError, expression2
82\end{verbatim}
83
84These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000085\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000086variables with those names. In the current implementation, the
87built-in variable \code{__debug__} is 1 under normal circumstances, 0
88when optimization is requested (command line option -O). The current
89code generator emits no code for an assert statement when optimization
90is requested at compile time. Note that it is unnecessary to include
91the source code for the expression that failed in the error message;
92it will be displayed as part of the stack trace.
93
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000094Assignments to \code{__debug__} are illegal. The value for the
95built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000096
Fred Drake2829f1c2001-06-23 05:27:20 +000097
Fred Drake011f6fc1999-04-14 12:52:14 +000098\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000099
Fred Drake011f6fc1999-04-14 12:52:14 +0000100Assignment statements\indexii{assignment}{statement} are used to
101(re)bind names to values and to modify attributes or items of mutable
102objects:
Fred Drakef6669171998-05-06 19:52:49 +0000103\indexii{binding}{name}
104\indexii{rebinding}{name}
105\obindex{mutable}
106\indexii{attribute}{assignment}
107
Fred Drakecb4638a2001-07-06 22:49:53 +0000108\begin{productionlist}
109 \production{assignment_stmt}
110 {(\token{target_list} "=")+ \token{expression_list}}
111 \production{target_list}
112 {\token{target} ("," \token{target})* [","]}
113 \production{target}
114 {\token{identifier}
115 | "(" \token{target_list} ")"
116 | "[" \token{target_list} "]"
117 | \token{attributeref}
118 | \token{subscription}
119 | \token{slicing}}
120\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000121
Fred Drakec2f496a2001-12-05 05:46:25 +0000122(See section~\ref{primaries} for the syntax definitions for the last
Fred Drakef6669171998-05-06 19:52:49 +0000123three symbols.)
124
125An assignment statement evaluates the expression list (remember that
126this can be a single expression or a comma-separated list, the latter
127yielding a tuple) and assigns the single resulting object to each of
128the target lists, from left to right.
129\indexii{expression}{list}
130
131Assignment is defined recursively depending on the form of the target
132(list). When a target is part of a mutable object (an attribute
133reference, subscription or slicing), the mutable object must
134ultimately perform the assignment and decide about its validity, and
135may raise an exception if the assignment is unacceptable. The rules
136observed by various types and the exceptions raised are given with the
Fred Drakec2f496a2001-12-05 05:46:25 +0000137definition of the object types (see section~\ref{types}).
Fred Drakef6669171998-05-06 19:52:49 +0000138\index{target}
139\indexii{target}{list}
140
141Assignment of an object to a target list is recursively defined as
142follows.
143\indexiii{target}{list}{assignment}
144
145\begin{itemize}
146\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000147If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000148target.
149
150\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000151If the target list is a comma-separated list of targets: The object
152must be a sequence with the same number of items as the there are
153targets in the target list, and the items are assigned, from left to
154right, to the corresponding targets. (This rule is relaxed as of
155Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000156strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000157now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000158
159\end{itemize}
160
161Assignment of an object to a single target is recursively defined as
162follows.
163
164\begin{itemize} % nested
165
166\item
167If the target is an identifier (name):
168
169\begin{itemize}
170
171\item
172If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000173code block: the name is bound to the object in the current local
174namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000175\stindex{global}
176
177\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000178Otherwise: the name is bound to the object in the current global
179namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000180
181\end{itemize} % nested
182
Guido van Rossum56c20131998-07-24 18:25:38 +0000183The name is rebound if it was already bound. This may cause the
184reference count for the object previously bound to the name to reach
185zero, causing the object to be deallocated and its
186destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000187
188\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000189If the target is a target list enclosed in parentheses or in square
190brackets: The object must be a sequence with the same number of items
191as there are targets in the target list, and its items are assigned,
192from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000193
194\item
195If the target is an attribute reference: The primary expression in the
196reference is evaluated. It should yield an object with assignable
197attributes; if this is not the case, \exception{TypeError} is raised. That
198object is then asked to assign the assigned object to the given
199attribute; if it cannot perform the assignment, it raises an exception
200(usually but not necessarily \exception{AttributeError}).
201\indexii{attribute}{assignment}
202
203\item
204If the target is a subscription: The primary expression in the
205reference is evaluated. It should yield either a mutable sequence
Guido van Rossum56c20131998-07-24 18:25:38 +0000206object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
207the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000208\indexii{subscription}{assignment}
209\obindex{mutable}
210
Guido van Rossum56c20131998-07-24 18:25:38 +0000211If the primary is a mutable sequence object (e.g., a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000212must yield a plain integer. If it is negative, the sequence's length
213is added to it. The resulting value must be a nonnegative integer
214less than the sequence's length, and the sequence is asked to assign
215the assigned object to its item with that index. If the index is out
216of range, \exception{IndexError} is raised (assignment to a subscripted
217sequence cannot add new items to a list).
218\obindex{sequence}
219\obindex{list}
220
Guido van Rossum56c20131998-07-24 18:25:38 +0000221If the primary is a mapping object (e.g., a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000222have a type compatible with the mapping's key type, and the mapping is
223then asked to create a key/datum pair which maps the subscript to
224the assigned object. This can either replace an existing key/value
225pair with the same key value, or insert a new key/value pair (if no
226key with the same value existed).
227\obindex{mapping}
228\obindex{dictionary}
229
230\item
231If the target is a slicing: The primary expression in the reference is
Guido van Rossum56c20131998-07-24 18:25:38 +0000232evaluated. It should yield a mutable sequence object (e.g., a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000233assigned object should be a sequence object of the same type. Next,
234the lower and upper bound expressions are evaluated, insofar they are
235present; defaults are zero and the sequence's length. The bounds
236should evaluate to (small) integers. If either bound is negative, the
237sequence's length is added to it. The resulting bounds are clipped to
238lie between zero and the sequence's length, inclusive. Finally, the
239sequence object is asked to replace the slice with the items of the
240assigned sequence. The length of the slice may be different from the
241length of the assigned sequence, thus changing the length of the
242target sequence, if the object allows it.
243\indexii{slicing}{assignment}
244
245\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000246
Fred Drakef6669171998-05-06 19:52:49 +0000247(In the current implementation, the syntax for targets is taken
248to be the same as for expressions, and invalid syntax is rejected
249during the code generation phase, causing less detailed error
250messages.)
251
252WARNING: Although the definition of assignment implies that overlaps
Guido van Rossum56c20131998-07-24 18:25:38 +0000253between the left-hand side and the right-hand side are `safe' (e.g.,
Fred Drake011f6fc1999-04-14 12:52:14 +0000254\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000255collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000256following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000257
258\begin{verbatim}
259x = [0, 1]
260i = 0
261i, x[i] = 1, 2
262print x
263\end{verbatim}
264
265
Fred Drake31f55502000-09-12 20:32:18 +0000266\subsection{Augmented Assignment statements \label{augassign}}
267
268Augmented assignment is the combination, in a single statement, of a binary
269operation and an assignment statement:
270\indexii{augmented}{assignment}
271\index{statement!assignment, augmented}
272
Fred Drakecb4638a2001-07-06 22:49:53 +0000273\begin{productionlist}
274 \production{augmented_assignment_stmt}
275 {\token{target} \token{augop} \token{expression_list}}
276 \production{augop}
277 {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="
278 | ">>=" | "<<=" | "\&=" | "\textasciicircum=" | "|="}
279 \production{target}
280 {\token{identifier}
281 | "(" \token{target_list} ")"
282 | "[" \token{target_list} "]"
283 | \token{attributeref}
284 | \token{subscription}
285 | \token{slicing}}
286\end{productionlist}
Fred Drake31f55502000-09-12 20:32:18 +0000287
Fred Drakec2f496a2001-12-05 05:46:25 +0000288(See section~\ref{primaries} for the syntax definitions for the last
Fred Drake31f55502000-09-12 20:32:18 +0000289three symbols.)
290
Fred Draked68442b2000-09-21 22:01:36 +0000291An augmented assignment evaluates the target (which, unlike normal
292assignment statements, cannot be an unpacking) and the expression
293list, performs the binary operation specific to the type of assignment
294on the two operands, and assigns the result to the original
295target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000296
297An augmented assignment expression like \code{x += 1} can be rewritten as
298\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
299augmented version, \code{x} is only evaluated once. Also, when possible, the
300actual operation is performed \emph{in-place}, meaning that rather than
301creating a new object and assigning that to the target, the old object is
302modified instead.
303
304With the exception of assigning to tuples and multiple targets in a single
305statement, the assignment done by augmented assignment statements is handled
306the same way as normal assignments. Similarly, with the exception of the
Fred Drakec2f496a2001-12-05 05:46:25 +0000307possible \emph{in-place} behavior, the binary operation performed by
Fred Drake31f55502000-09-12 20:32:18 +0000308augmented assignment is the same as the normal binary operations.
309
310
Fred Drake011f6fc1999-04-14 12:52:14 +0000311\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000312\stindex{pass}
313
Fred Drakecb4638a2001-07-06 22:49:53 +0000314\begin{productionlist}
315 \production{pass_stmt}
316 {"pass"}
317\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000318
319\keyword{pass} is a null operation --- when it is executed, nothing
320happens. It is useful as a placeholder when a statement is
321required syntactically, but no code needs to be executed, for example:
322\indexii{null}{operation}
323
324\begin{verbatim}
325def f(arg): pass # a function that does nothing (yet)
326
327class C: pass # a class with no methods (yet)
328\end{verbatim}
329
Fred Drake2829f1c2001-06-23 05:27:20 +0000330
Fred Drake011f6fc1999-04-14 12:52:14 +0000331\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000332\stindex{del}
333
Fred Drakecb4638a2001-07-06 22:49:53 +0000334\begin{productionlist}
335 \production{del_stmt}
336 {"del" \token{target_list}}
337\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000338
339Deletion is recursively defined very similar to the way assignment is
340defined. Rather that spelling it out in full details, here are some
341hints.
342\indexii{deletion}{target}
343\indexiii{deletion}{target}{list}
344
345Deletion of a target list recursively deletes each target, from left
346to right.
347
348Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum56c20131998-07-24 18:25:38 +0000349from the local or global namespace, depending on whether the name
Fred Drakef6669171998-05-06 19:52:49 +0000350occurs in a \keyword{global} statement in the same code block.
351\stindex{global}
352\indexii{unbinding}{name}
353
354Deletion of attribute references, subscriptions and slicings
355is passed to the primary object involved; deletion of a slicing
356is in general equivalent to assignment of an empty slice of the
357right type (but even this is determined by the sliced object).
358\indexii{attribute}{deletion}
359
Fred Drake2829f1c2001-06-23 05:27:20 +0000360
Fred Drake011f6fc1999-04-14 12:52:14 +0000361\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000362\stindex{print}
363
Fred Drakecb4638a2001-07-06 22:49:53 +0000364\begin{productionlist}
365 \production{print_stmt}
366 {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}
367 | ">\code{>}" \token{expression}
368 \optional{("," \token{expression})+ \optional{","}})}
369\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000370
Fred Draked4c33521998-10-01 20:39:47 +0000371\keyword{print} evaluates each expression in turn and writes the
372resulting object to standard output (see below). If an object is not
Fred Drakebe9d10e2001-06-23 06:16:52 +0000373a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000374conversions. The (resulting or original) string is then written. A
Fred Drakebe9d10e2001-06-23 06:16:52 +0000375space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000376the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000377line. This is the case (1) when no characters have yet been written
378to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000379output is \character{\e n}, or (3) when the last write operation on
380standard output was not a \keyword{print} statement. (In some cases
381it may be functional to write an empty string to standard output for
Fred Drakec2f496a2001-12-05 05:46:25 +0000382this reason.) \note{Objects which act like file objects but which are
383not the built-in file objects often do not properly emulate this
384aspect of the file object's behavior, so it is best not to rely on
385this.}
Fred Drakef6669171998-05-06 19:52:49 +0000386\index{output}
387\indexii{writing}{values}
388
Fred Draked4c33521998-10-01 20:39:47 +0000389A \character{\e n} character is written at the end, unless the
390\keyword{print} statement ends with a comma. This is the only action
391if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000392\indexii{trailing}{comma}
393\indexii{newline}{suppression}
394
Fred Drakedde91f01998-05-06 20:59:46 +0000395Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000396in the built-in module \module{sys}. If no such object exists, or if
397it does not have a \method{write()} method, a \exception{RuntimeError}
398exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000399\indexii{standard}{output}
400\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000401\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000402\exindex{RuntimeError}
403
Fred Drakecb4638a2001-07-06 22:49:53 +0000404\keyword{print} also has an extended\index{extended print statement}
405form, defined by the second portion of the syntax described above.
406This form is sometimes referred to as ``\keyword{print} chevron.''
Fred Drake62effc12001-04-13 15:55:25 +0000407In this form, the first expression after the \code{>}\code{>} must
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000408evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000409\method{write()} method as described above. With this extended form,
410the subsequent expressions are printed to this file object. If the
411first expression evaluates to \code{None}, then \code{sys.stdout} is
412used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000413
Fred Drake2829f1c2001-06-23 05:27:20 +0000414
Fred Drake011f6fc1999-04-14 12:52:14 +0000415\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000416\stindex{return}
417
Fred Drakecb4638a2001-07-06 22:49:53 +0000418\begin{productionlist}
419 \production{return_stmt}
420 {"return" [\token{expression_list}]}
421\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000422
423\keyword{return} may only occur syntactically nested in a function
424definition, not within a nested class definition.
425\indexii{function}{definition}
426\indexii{class}{definition}
427
Guido van Rossum56c20131998-07-24 18:25:38 +0000428If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000429is substituted.
430
Guido van Rossum56c20131998-07-24 18:25:38 +0000431\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000432list (or \code{None}) as return value.
433
434When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000435with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000436before really leaving the function.
437\kwindex{finally}
438
Fred Drake2829f1c2001-06-23 05:27:20 +0000439
Fred Drake011f6fc1999-04-14 12:52:14 +0000440\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000441\stindex{raise}
442
Fred Drakecb4638a2001-07-06 22:49:53 +0000443\begin{productionlist}
444 \production{raise_stmt}
445 {"raise" [\token{expression} ["," \token{expression}
446 ["," \token{expression}]]]}
447\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000448
Guido van Rossum56c20131998-07-24 18:25:38 +0000449If no expressions are present, \keyword{raise} re-raises the last
450expression that was raised in the current scope.
451
Fred Drake011f6fc1999-04-14 12:52:14 +0000452Otherwise, \keyword{raise} evaluates its first expression, which must yield
Guido van Rossum56c20131998-07-24 18:25:38 +0000453a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000454this is evaluated, else \code{None} is substituted. If the first
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000455expression is a class object, then the second expression may be an
456instance of that class or one of its derivatives, and then that
457instance is raised. If the second expression is not such an instance,
458the given class is instantiated. The argument list for the
459instantiation is determined as follows: if the second expression is a
460tuple, it is used as the argument list; if it is \code{None}, the
461argument list is empty; otherwise, the argument list consists of a
462single argument which is the second expression. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000463expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000464\code{None}.
465\index{exception}
466\indexii{raising}{exception}
467
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000468If the first object is a string, it then raises the exception
Fred Drakef6669171998-05-06 19:52:49 +0000469identified by the first object, with the second one (or \code{None})
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000470as its parameter. If the first object is a class or instance,
471it raises the exception identified by the class of the instance
472determined in the previous step, with the instance as
473its parameter.
Fred Drakef6669171998-05-06 19:52:49 +0000474
Guido van Rossum56c20131998-07-24 18:25:38 +0000475If a third object is present, and it is not \code{None}, it should be
Fred Drakec2f496a2001-12-05 05:46:25 +0000476a traceback object (see section~\ref{traceback}), and it is
Fred Drakef6669171998-05-06 19:52:49 +0000477substituted instead of the current location as the place where the
478exception occurred. This is useful to re-raise an exception
479transparently in an except clause.
480\obindex{traceback}
481
Fred Drake2829f1c2001-06-23 05:27:20 +0000482
Fred Drake011f6fc1999-04-14 12:52:14 +0000483\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000484\stindex{break}
485
Fred Drakecb4638a2001-07-06 22:49:53 +0000486\begin{productionlist}
487 \production{break_stmt}
488 {"break"}
489\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000490
491\keyword{break} may only occur syntactically nested in a \keyword{for}
492or \keyword{while} loop, but not nested in a function or class definition
493within that loop.
494\stindex{for}
495\stindex{while}
496\indexii{loop}{statement}
497
498It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000499\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000500\kwindex{else}
501
502If a \keyword{for} loop is terminated by \keyword{break}, the loop control
503target keeps its current value.
504\indexii{loop control}{target}
505
506When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000507with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000508before really leaving the loop.
509\kwindex{finally}
510
Fred Drake2829f1c2001-06-23 05:27:20 +0000511
Fred Drake011f6fc1999-04-14 12:52:14 +0000512\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000513\stindex{continue}
514
Fred Drakecb4638a2001-07-06 22:49:53 +0000515\begin{productionlist}
516 \production{continue_stmt}
517 {"continue"}
518\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000519
520\keyword{continue} may only occur syntactically nested in a \keyword{for} or
521\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000522\keyword{try} statement within that loop.\footnote{It may
523occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000524restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000525laziness and will eventually be lifted.}
526It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000527\stindex{for}
528\stindex{while}
529\indexii{loop}{statement}
530\kwindex{finally}
531
Fred Drake2829f1c2001-06-23 05:27:20 +0000532
Fred Drake011f6fc1999-04-14 12:52:14 +0000533\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000534\stindex{import}
535
Fred Drakecb4638a2001-07-06 22:49:53 +0000536\begin{productionlist}
537 \production{import_stmt}
538 {"import" \token{module} ["as" \token{name}]
539 ( "," \token{module} ["as" \token{name}] )*
540 | "from" \token{module} "import" \token{identifier}
541 ["as" \token{name}]
542 ( "," \token{identifier} ["as" \token{name}] )*
543 | "from" \token{module} "import" "*"}
544 \production{module}
545 {(\token{identifier} ".")* \token{identifier}}
546\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000547
548Import statements are executed in two steps: (1) find a module, and
549initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000550namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000551The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000552identifier in the list. The form with \keyword{from} performs step
553(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000554\indexii{importing}{module}
555\indexii{name}{binding}
556\kwindex{from}
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000557% XXX Need to define what ``initialize'' means here
Fred Drakef6669171998-05-06 19:52:49 +0000558
559The system maintains a table of modules that have been initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000560indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000561accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000562this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000563definition is started. When a module is found, it is loaded. Details
564of the module searching and loading process are implementation and
565platform specific. It generally involves searching for a ``built-in''
566module with the given name and then searching a list of locations
567given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000568\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000569\ttindex{sys.modules}
570\indexii{module}{name}
571\indexii{built-in}{module}
572\indexii{user-defined}{module}
573\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000574\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000575\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000576
577If a built-in module is found, its built-in initialization code is
578executed and step (1) is finished. If no matching file is found,
579\exception{ImportError} is raised. If a file is found, it is parsed,
580yielding an executable code block. If a syntax error occurs,
581\exception{SyntaxError} is raised. Otherwise, an empty module of the given
582name is created and inserted in the module table, and then the code
583block is executed in the context of this module. Exceptions during
584this execution terminate step (1).
585\indexii{module}{initialization}
586\exindex{SyntaxError}
587\exindex{ImportError}
588\index{code block}
589
590When step (1) finishes without raising an exception, step (2) can
591begin.
592
Fred Drake859eb622001-03-06 07:34:00 +0000593The first form of \keyword{import} statement binds the module name in
594the local namespace to the module object, and then goes on to import
595the next identifier, if any. If the module name is followed by
596\keyword{as}, the name following \keyword{as} is used as the local
597name for the module. To avoid confusion, you cannot import modules
598with dotted names \keyword{as} a different local name. So \code{import
599module as m} is legal, but \code{import module.submod as s} is not.
600The latter should be written as \code{from module import submod as s};
Thomas Wouters8bad6122000-08-19 20:55:02 +0000601see below.
602
Thomas Wouters52152252000-08-17 22:55:00 +0000603The \keyword{from} form does not bind the module name: it goes through the
604list of identifiers, looks each one of them up in the module found in step
605(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000606As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000607supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000608\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drake08fd5152001-10-24 19:50:31 +0000609by a star (\character{*}), all public names defined in the module are
610bound in the local namespace of the \keyword{import} statement..
Fred Drakef6669171998-05-06 19:52:49 +0000611\indexii{name}{binding}
612\exindex{ImportError}
613
Fred Drake08fd5152001-10-24 19:50:31 +0000614The \emph{public names} defined by a module are determined by checking
615the module's namespace for a variable named \code{__all__}; if
616defined, it must be a sequence of strings which are names defined or
617imported by that module. The names given in \code{__all__} are all
618considered public and are required to exist. If \code{__all__} is not
619defined, the set of public names includes all names found in the
620module's namespace which do not begin with an underscore character
621(\character{_}).
622
Guido van Rossum56c20131998-07-24 18:25:38 +0000623Names bound by \keyword{import} statements may not occur in
624\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000625\stindex{global}
626
Fred Drake011f6fc1999-04-14 12:52:14 +0000627The \keyword{from} form with \samp{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000628\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000629\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000630
Fred Drake246837d1998-07-24 20:28:22 +0000631\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000632when the module names contains one or more dots, the module search
633path is carried out differently. The sequence of identifiers up to
634the last dot is used to find a ``package''\index{packages}; the final
635identifier is then searched inside the package. A package is
636generally a subdirectory of a directory on \code{sys.path} that has a
637file \file{__init__.py}.\ttindex{__init__.py}
638%
639[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000640\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000641about how the module search works from inside a package.]
642
Fred Drake08fd5152001-10-24 19:50:31 +0000643The built-in function \function{__import__()} is provided to support
644applications that determine which modules need to be loaded
645dynamically; refer to \ulink{Built-in
646Functions}{../lib/built-in-funcs.html} in the
647\citetitle[../lib/lib.html]{Python Library Reference} for additional
648information.
Guido van Rossum56c20131998-07-24 18:25:38 +0000649\bifuncindex{__import__}
650
Fred Drake2829f1c2001-06-23 05:27:20 +0000651
Fred Drake011f6fc1999-04-14 12:52:14 +0000652\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000653\stindex{global}
654
Fred Drakecb4638a2001-07-06 22:49:53 +0000655\begin{productionlist}
656 \production{global_stmt}
657 {"global" \token{identifier} ("," \token{identifier})*}
658\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000659
660The \keyword{global} statement is a declaration which holds for the
661entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000662interpreted as globals. While \emph{using} global names is automatic
663if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000664names would be impossible without \keyword{global}.
665\indexiii{global}{name}{binding}
666
667Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000668code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000669
670Names listed in a \keyword{global} statement must not be defined as formal
671parameters or in a \keyword{for} loop control target, \keyword{class}
672definition, function definition, or \keyword{import} statement.
673
674(The current implementation does not enforce the latter two
675restrictions, but programs should not abuse this freedom, as future
676implementations may enforce them or silently change the meaning of the
677program.)
678
Guido van Rossum56c20131998-07-24 18:25:38 +0000679\strong{Programmer's note:}
680the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000681applies only to code parsed at the same time as the \keyword{global}
682statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000683\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000684the \keyword{exec} statement, and code contained in an \keyword{exec}
685statement is unaffected by \keyword{global} statements in the code
686containing the \keyword{exec} statement. The same applies to the
687\function{eval()}, \function{execfile()} and \function{compile()} functions.
688\stindex{exec}
689\bifuncindex{eval}
690\bifuncindex{execfile}
691\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000692
Fred Drake2829f1c2001-06-23 05:27:20 +0000693
Fred Drake011f6fc1999-04-14 12:52:14 +0000694\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000695\stindex{exec}
696
Fred Drakecb4638a2001-07-06 22:49:53 +0000697\begin{productionlist}
698 \production{exec_stmt}
699 {"exec" \token{expression}
700 ["in" \token{expression} ["," \token{expression}]]}
701\end{productionlist}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000702
703This statement supports dynamic execution of Python code. The first
704expression should evaluate to either a string, an open file object, or
705a code object. If it is a string, the string is parsed as a suite of
706Python statements which is then executed (unless a syntax error
Fred Drake93852ef2001-06-23 06:06:52 +0000707occurs). If it is an open file, the file is parsed until \EOF{} and
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000708executed. If it is a code object, it is simply executed.
709
710In all cases, if the optional parts are omitted, the code is executed
711in the current scope. If only the first expression after \keyword{in}
712is specified, it should be a dictionary, which will be used for both
713the global and the local variables. If two expressions are given,
714both must be dictionaries and they are used for the global and local
715variables, respectively.
716
717As a side effect, an implementation may insert additional keys into
718the dictionaries given besides those corresponding to variable names
719set by the executed code. For example, the current implementation
720may add a reference to the dictionary of the built-in module
721\module{__builtin__} under the key \code{__builtins__} (!).
722\ttindex{__builtins__}
723\refbimodindex{__builtin__}
724
Guido van Rossum56c20131998-07-24 18:25:38 +0000725\strong{Programmer's hints:}
726dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000727function \function{eval()}. The built-in functions
728\function{globals()} and \function{locals()} return the current global
729and local dictionary, respectively, which may be useful to pass around
730for use by \keyword{exec}.
731\bifuncindex{eval}
732\bifuncindex{globals}
733\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000734
735Also, in the current implementation, multi-line compound statements must
736end with a newline:
737\code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
738\code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
739\exception{SyntaxError}.
740\exindex{SyntaxError}
741
742