blob: 9922fe7eb353395c0d5aa171aee59cb387f33461 [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
8\begin{verbatim}
9simple_stmt: expression_stmt
Guido van Rossum56c20131998-07-24 18:25:38 +000010 | assert_stmt
Fred Drakef6669171998-05-06 19:52:49 +000011 | assignment_stmt
Fred Drake31f55502000-09-12 20:32:18 +000012 | augmented_assignment_stmt
Fred Drakef6669171998-05-06 19:52:49 +000013 | pass_stmt
14 | del_stmt
15 | print_stmt
16 | return_stmt
17 | raise_stmt
18 | break_stmt
19 | continue_stmt
20 | import_stmt
21 | global_stmt
22 | exec_stmt
23\end{verbatim}
24
Fred Drake2829f1c2001-06-23 05:27:20 +000025
Fred Drake011f6fc1999-04-14 12:52:14 +000026\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000027\indexii{expression}{statement}
28
29Expression statements are used (mostly interactively) to compute and
30write a value, or (usually) to call a procedure (a function that
31returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000032\code{None}). Other uses of expression statements are allowed and
33occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000034
35\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +000036expression_stmt: expression_list
Fred Drakef6669171998-05-06 19:52:49 +000037\end{verbatim}
38
Guido van Rossum56c20131998-07-24 18:25:38 +000039An expression statement evaluates the expression list (which may be a
40single expression).
Fred Drakef6669171998-05-06 19:52:49 +000041\indexii{expression}{list}
42
43In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000044to a string using the built-in \function{repr()}\bifuncindex{repr}
45function and the resulting string is written to standard output (see
46section \ref{print}) on a line by itself. (Expression statements
47yielding None are not written, so that procedure calls do not cause
48any output.)
Fred Drakef6669171998-05-06 19:52:49 +000049\ttindex{None}
50\indexii{string}{conversion}
51\index{output}
52\indexii{standard}{output}
53\indexii{writing}{values}
54\indexii{procedure}{call}
55
Fred Drake2829f1c2001-06-23 05:27:20 +000056
Fred Drake011f6fc1999-04-14 12:52:14 +000057\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000058
Fred Drake011f6fc1999-04-14 12:52:14 +000059Assert statements\stindex{assert} are a convenient way to insert
60debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000061
62\begin{verbatim}
63assert_statement: "assert" expression ["," expression]
64\end{verbatim}
65
Fred Drake011f6fc1999-04-14 12:52:14 +000066The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000067
68\begin{verbatim}
69if __debug__:
70 if not expression: raise AssertionError
71\end{verbatim}
72
Fred Drake011f6fc1999-04-14 12:52:14 +000073The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000074equivalent to
75
76\begin{verbatim}
77if __debug__:
78 if not expression1: raise AssertionError, expression2
79\end{verbatim}
80
81These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000082\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000083variables with those names. In the current implementation, the
84built-in variable \code{__debug__} is 1 under normal circumstances, 0
85when optimization is requested (command line option -O). The current
86code generator emits no code for an assert statement when optimization
87is requested at compile time. Note that it is unnecessary to include
88the source code for the expression that failed in the error message;
89it will be displayed as part of the stack trace.
90
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000091Assignments to \code{__debug__} are illegal. The value for the
92built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000093
Fred Drake2829f1c2001-06-23 05:27:20 +000094
Fred Drake011f6fc1999-04-14 12:52:14 +000095\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000096
Fred Drake011f6fc1999-04-14 12:52:14 +000097Assignment statements\indexii{assignment}{statement} are used to
98(re)bind names to values and to modify attributes or items of mutable
99objects:
Fred Drakef6669171998-05-06 19:52:49 +0000100\indexii{binding}{name}
101\indexii{rebinding}{name}
102\obindex{mutable}
103\indexii{attribute}{assignment}
104
105\begin{verbatim}
106assignment_stmt: (target_list "=")+ expression_list
107target_list: target ("," target)* [","]
108target: identifier | "(" target_list ")" | "[" target_list "]"
109 | attributeref | subscription | slicing
110\end{verbatim}
111
112(See section \ref{primaries} for the syntax definitions for the last
113three symbols.)
114
115An assignment statement evaluates the expression list (remember that
116this can be a single expression or a comma-separated list, the latter
117yielding a tuple) and assigns the single resulting object to each of
118the target lists, from left to right.
119\indexii{expression}{list}
120
121Assignment is defined recursively depending on the form of the target
122(list). When a target is part of a mutable object (an attribute
123reference, subscription or slicing), the mutable object must
124ultimately perform the assignment and decide about its validity, and
125may raise an exception if the assignment is unacceptable. The rules
126observed by various types and the exceptions raised are given with the
127definition of the object types (see section \ref{types}).
128\index{target}
129\indexii{target}{list}
130
131Assignment of an object to a target list is recursively defined as
132follows.
133\indexiii{target}{list}{assignment}
134
135\begin{itemize}
136\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000137If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000138target.
139
140\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000141If the target list is a comma-separated list of targets: The object
142must be a sequence with the same number of items as the there are
143targets in the target list, and the items are assigned, from left to
144right, to the corresponding targets. (This rule is relaxed as of
145Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000146strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000147now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000148
149\end{itemize}
150
151Assignment of an object to a single target is recursively defined as
152follows.
153
154\begin{itemize} % nested
155
156\item
157If the target is an identifier (name):
158
159\begin{itemize}
160
161\item
162If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000163code block: the name is bound to the object in the current local
164namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000165\stindex{global}
166
167\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000168Otherwise: the name is bound to the object in the current global
169namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000170
171\end{itemize} % nested
172
Guido van Rossum56c20131998-07-24 18:25:38 +0000173The name is rebound if it was already bound. This may cause the
174reference count for the object previously bound to the name to reach
175zero, causing the object to be deallocated and its
176destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000177
178\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000179If the target is a target list enclosed in parentheses or in square
180brackets: The object must be a sequence with the same number of items
181as there are targets in the target list, and its items are assigned,
182from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000183
184\item
185If the target is an attribute reference: The primary expression in the
186reference is evaluated. It should yield an object with assignable
187attributes; if this is not the case, \exception{TypeError} is raised. That
188object is then asked to assign the assigned object to the given
189attribute; if it cannot perform the assignment, it raises an exception
190(usually but not necessarily \exception{AttributeError}).
191\indexii{attribute}{assignment}
192
193\item
194If the target is a subscription: The primary expression in the
195reference is evaluated. It should yield either a mutable sequence
Guido van Rossum56c20131998-07-24 18:25:38 +0000196object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
197the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000198\indexii{subscription}{assignment}
199\obindex{mutable}
200
Guido van Rossum56c20131998-07-24 18:25:38 +0000201If the primary is a mutable sequence object (e.g., a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000202must yield a plain integer. If it is negative, the sequence's length
203is added to it. The resulting value must be a nonnegative integer
204less than the sequence's length, and the sequence is asked to assign
205the assigned object to its item with that index. If the index is out
206of range, \exception{IndexError} is raised (assignment to a subscripted
207sequence cannot add new items to a list).
208\obindex{sequence}
209\obindex{list}
210
Guido van Rossum56c20131998-07-24 18:25:38 +0000211If the primary is a mapping object (e.g., a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000212have a type compatible with the mapping's key type, and the mapping is
213then asked to create a key/datum pair which maps the subscript to
214the assigned object. This can either replace an existing key/value
215pair with the same key value, or insert a new key/value pair (if no
216key with the same value existed).
217\obindex{mapping}
218\obindex{dictionary}
219
220\item
221If the target is a slicing: The primary expression in the reference is
Guido van Rossum56c20131998-07-24 18:25:38 +0000222evaluated. It should yield a mutable sequence object (e.g., a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000223assigned object should be a sequence object of the same type. Next,
224the lower and upper bound expressions are evaluated, insofar they are
225present; defaults are zero and the sequence's length. The bounds
226should evaluate to (small) integers. If either bound is negative, the
227sequence's length is added to it. The resulting bounds are clipped to
228lie between zero and the sequence's length, inclusive. Finally, the
229sequence object is asked to replace the slice with the items of the
230assigned sequence. The length of the slice may be different from the
231length of the assigned sequence, thus changing the length of the
232target sequence, if the object allows it.
233\indexii{slicing}{assignment}
234
235\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000236
Fred Drakef6669171998-05-06 19:52:49 +0000237(In the current implementation, the syntax for targets is taken
238to be the same as for expressions, and invalid syntax is rejected
239during the code generation phase, causing less detailed error
240messages.)
241
242WARNING: Although the definition of assignment implies that overlaps
Guido van Rossum56c20131998-07-24 18:25:38 +0000243between the left-hand side and the right-hand side are `safe' (e.g.,
Fred Drake011f6fc1999-04-14 12:52:14 +0000244\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000245collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000246following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000247
248\begin{verbatim}
249x = [0, 1]
250i = 0
251i, x[i] = 1, 2
252print x
253\end{verbatim}
254
255
Fred Drake31f55502000-09-12 20:32:18 +0000256\subsection{Augmented Assignment statements \label{augassign}}
257
258Augmented assignment is the combination, in a single statement, of a binary
259operation and an assignment statement:
260\indexii{augmented}{assignment}
261\index{statement!assignment, augmented}
262
263\begin{verbatim}
264augmented_assignment_stmt: target augop expression_list
265augop: "+=" | "-=" | "*=" | "/=" | "%=" | "**="
266 | ">>=" | "<<=" | "&=" | "^=" | "|="
267target: identifier | "(" target_list ")" | "[" target_list "]"
268 | attributeref | subscription | slicing
269\end{verbatim}
270
271(See section \ref{primaries} for the syntax definitions for the last
272three symbols.)
273
Fred Draked68442b2000-09-21 22:01:36 +0000274An augmented assignment evaluates the target (which, unlike normal
275assignment statements, cannot be an unpacking) and the expression
276list, performs the binary operation specific to the type of assignment
277on the two operands, and assigns the result to the original
278target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000279
280An augmented assignment expression like \code{x += 1} can be rewritten as
281\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
282augmented version, \code{x} is only evaluated once. Also, when possible, the
283actual operation is performed \emph{in-place}, meaning that rather than
284creating a new object and assigning that to the target, the old object is
285modified instead.
286
287With the exception of assigning to tuples and multiple targets in a single
288statement, the assignment done by augmented assignment statements is handled
289the same way as normal assignments. Similarly, with the exception of the
290possible \emph{in-place} behaviour, the binary operation performed by
291augmented assignment is the same as the normal binary operations.
292
293
Fred Drake011f6fc1999-04-14 12:52:14 +0000294\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000295\stindex{pass}
296
297\begin{verbatim}
298pass_stmt: "pass"
299\end{verbatim}
300
301\keyword{pass} is a null operation --- when it is executed, nothing
302happens. It is useful as a placeholder when a statement is
303required syntactically, but no code needs to be executed, for example:
304\indexii{null}{operation}
305
306\begin{verbatim}
307def f(arg): pass # a function that does nothing (yet)
308
309class C: pass # a class with no methods (yet)
310\end{verbatim}
311
Fred Drake2829f1c2001-06-23 05:27:20 +0000312
Fred Drake011f6fc1999-04-14 12:52:14 +0000313\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000314\stindex{del}
315
316\begin{verbatim}
317del_stmt: "del" target_list
318\end{verbatim}
319
320Deletion is recursively defined very similar to the way assignment is
321defined. Rather that spelling it out in full details, here are some
322hints.
323\indexii{deletion}{target}
324\indexiii{deletion}{target}{list}
325
326Deletion of a target list recursively deletes each target, from left
327to right.
328
329Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum56c20131998-07-24 18:25:38 +0000330from the local or global namespace, depending on whether the name
Fred Drakef6669171998-05-06 19:52:49 +0000331occurs in a \keyword{global} statement in the same code block.
332\stindex{global}
333\indexii{unbinding}{name}
334
335Deletion of attribute references, subscriptions and slicings
336is passed to the primary object involved; deletion of a slicing
337is in general equivalent to assignment of an empty slice of the
338right type (but even this is determined by the sliced object).
339\indexii{attribute}{deletion}
340
Fred Drake2829f1c2001-06-23 05:27:20 +0000341
Fred Drake011f6fc1999-04-14 12:52:14 +0000342\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000343\stindex{print}
344
345\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000346print_stmt: "print" [ expression ("," expression)* [","] ]
Fred Drakef6669171998-05-06 19:52:49 +0000347\end{verbatim}
348
Fred Draked4c33521998-10-01 20:39:47 +0000349\keyword{print} evaluates each expression in turn and writes the
350resulting object to standard output (see below). If an object is not
Fred Drakebe9d10e2001-06-23 06:16:52 +0000351a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000352conversions. The (resulting or original) string is then written. A
Fred Drakebe9d10e2001-06-23 06:16:52 +0000353space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000354the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000355line. This is the case (1) when no characters have yet been written
356to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000357output is \character{\e n}, or (3) when the last write operation on
358standard output was not a \keyword{print} statement. (In some cases
359it may be functional to write an empty string to standard output for
360this reason.)
Fred Drakef6669171998-05-06 19:52:49 +0000361\index{output}
362\indexii{writing}{values}
363
Fred Draked4c33521998-10-01 20:39:47 +0000364A \character{\e n} character is written at the end, unless the
365\keyword{print} statement ends with a comma. This is the only action
366if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000367\indexii{trailing}{comma}
368\indexii{newline}{suppression}
369
Fred Drakedde91f01998-05-06 20:59:46 +0000370Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000371in the built-in module \module{sys}. If no such object exists, or if
372it does not have a \method{write()} method, a \exception{RuntimeError}
373exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000374\indexii{standard}{output}
375\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000376\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000377\exindex{RuntimeError}
378
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000379\keyword{print} also has an extended form, defined as
Fred Draked68442b2000-09-21 22:01:36 +0000380\index{extended print statement}
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000381
382\begin{verbatim}
Fred Draked68442b2000-09-21 22:01:36 +0000383print_stmt: "print" ">>" expression [ ("," expression)+ [","] ]
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000384\end{verbatim}
385
Fred Drake62effc12001-04-13 15:55:25 +0000386In this form, the first expression after the \code{>}\code{>} must
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000387evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000388\method{write()} method as described above. With this extended form,
389the subsequent expressions are printed to this file object. If the
390first expression evaluates to \code{None}, then \code{sys.stdout} is
391used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000392
Fred Drake2829f1c2001-06-23 05:27:20 +0000393
Fred Drake011f6fc1999-04-14 12:52:14 +0000394\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000395\stindex{return}
396
397\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000398return_stmt: "return" [expression_list]
Fred Drakef6669171998-05-06 19:52:49 +0000399\end{verbatim}
400
401\keyword{return} may only occur syntactically nested in a function
402definition, not within a nested class definition.
403\indexii{function}{definition}
404\indexii{class}{definition}
405
Guido van Rossum56c20131998-07-24 18:25:38 +0000406If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000407is substituted.
408
Guido van Rossum56c20131998-07-24 18:25:38 +0000409\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000410list (or \code{None}) as return value.
411
412When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000413with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000414before really leaving the function.
415\kwindex{finally}
416
Fred Drake2829f1c2001-06-23 05:27:20 +0000417
Fred Drake011f6fc1999-04-14 12:52:14 +0000418\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000419\stindex{raise}
420
421\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000422raise_stmt: "raise" [expression ["," expression ["," expression]]]
Fred Drakef6669171998-05-06 19:52:49 +0000423\end{verbatim}
424
Guido van Rossum56c20131998-07-24 18:25:38 +0000425If no expressions are present, \keyword{raise} re-raises the last
426expression that was raised in the current scope.
427
Fred Drake011f6fc1999-04-14 12:52:14 +0000428Otherwise, \keyword{raise} evaluates its first expression, which must yield
Guido van Rossum56c20131998-07-24 18:25:38 +0000429a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000430this is evaluated, else \code{None} is substituted. If the first
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000431expression is a class object, then the second expression may be an
432instance of that class or one of its derivatives, and then that
433instance is raised. If the second expression is not such an instance,
434the given class is instantiated. The argument list for the
435instantiation is determined as follows: if the second expression is a
436tuple, it is used as the argument list; if it is \code{None}, the
437argument list is empty; otherwise, the argument list consists of a
438single argument which is the second expression. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000439expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000440\code{None}.
441\index{exception}
442\indexii{raising}{exception}
443
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000444If the first object is a string, it then raises the exception
Fred Drakef6669171998-05-06 19:52:49 +0000445identified by the first object, with the second one (or \code{None})
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000446as its parameter. If the first object is a class or instance,
447it raises the exception identified by the class of the instance
448determined in the previous step, with the instance as
449its parameter.
Fred Drakef6669171998-05-06 19:52:49 +0000450
Guido van Rossum56c20131998-07-24 18:25:38 +0000451If a third object is present, and it is not \code{None}, it should be
Fred Drakef6669171998-05-06 19:52:49 +0000452a traceback object (see section \ref{traceback}), and it is
453substituted instead of the current location as the place where the
454exception occurred. This is useful to re-raise an exception
455transparently in an except clause.
456\obindex{traceback}
457
Fred Drake2829f1c2001-06-23 05:27:20 +0000458
Fred Drake011f6fc1999-04-14 12:52:14 +0000459\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000460\stindex{break}
461
462\begin{verbatim}
463break_stmt: "break"
464\end{verbatim}
465
466\keyword{break} may only occur syntactically nested in a \keyword{for}
467or \keyword{while} loop, but not nested in a function or class definition
468within that loop.
469\stindex{for}
470\stindex{while}
471\indexii{loop}{statement}
472
473It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000474\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000475\kwindex{else}
476
477If a \keyword{for} loop is terminated by \keyword{break}, the loop control
478target keeps its current value.
479\indexii{loop control}{target}
480
481When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000482with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000483before really leaving the loop.
484\kwindex{finally}
485
Fred Drake2829f1c2001-06-23 05:27:20 +0000486
Fred Drake011f6fc1999-04-14 12:52:14 +0000487\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000488\stindex{continue}
489
490\begin{verbatim}
491continue_stmt: "continue"
492\end{verbatim}
493
494\keyword{continue} may only occur syntactically nested in a \keyword{for} or
495\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000496\keyword{try} statement within that loop.\footnote{It may
497occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000498restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000499laziness and will eventually be lifted.}
500It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000501\stindex{for}
502\stindex{while}
503\indexii{loop}{statement}
504\kwindex{finally}
505
Fred Drake2829f1c2001-06-23 05:27:20 +0000506
Fred Drake011f6fc1999-04-14 12:52:14 +0000507\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000508\stindex{import}
509
510\begin{verbatim}
Thomas Wouters52152252000-08-17 22:55:00 +0000511import_stmt: "import" module ["as" name] ("," module ["as" name] )*
512 | "from" module "import" identifier ["as" name]
513 ("," identifier ["as" name] )*
Guido van Rossum56c20131998-07-24 18:25:38 +0000514 | "from" module "import" "*"
515module: (identifier ".")* identifier
Fred Drakef6669171998-05-06 19:52:49 +0000516\end{verbatim}
517
518Import statements are executed in two steps: (1) find a module, and
519initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000520namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000521The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000522identifier in the list. The form with \keyword{from} performs step
523(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000524\indexii{importing}{module}
525\indexii{name}{binding}
526\kwindex{from}
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000527% XXX Need to define what ``initialize'' means here
Fred Drakef6669171998-05-06 19:52:49 +0000528
529The system maintains a table of modules that have been initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000530indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000531accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000532this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000533definition is started. When a module is found, it is loaded. Details
534of the module searching and loading process are implementation and
535platform specific. It generally involves searching for a ``built-in''
536module with the given name and then searching a list of locations
537given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000538\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000539\ttindex{sys.modules}
540\indexii{module}{name}
541\indexii{built-in}{module}
542\indexii{user-defined}{module}
543\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000544\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000545\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000546
547If a built-in module is found, its built-in initialization code is
548executed and step (1) is finished. If no matching file is found,
549\exception{ImportError} is raised. If a file is found, it is parsed,
550yielding an executable code block. If a syntax error occurs,
551\exception{SyntaxError} is raised. Otherwise, an empty module of the given
552name is created and inserted in the module table, and then the code
553block is executed in the context of this module. Exceptions during
554this execution terminate step (1).
555\indexii{module}{initialization}
556\exindex{SyntaxError}
557\exindex{ImportError}
558\index{code block}
559
560When step (1) finishes without raising an exception, step (2) can
561begin.
562
Fred Drake859eb622001-03-06 07:34:00 +0000563The first form of \keyword{import} statement binds the module name in
564the local namespace to the module object, and then goes on to import
565the next identifier, if any. If the module name is followed by
566\keyword{as}, the name following \keyword{as} is used as the local
567name for the module. To avoid confusion, you cannot import modules
568with dotted names \keyword{as} a different local name. So \code{import
569module as m} is legal, but \code{import module.submod as s} is not.
570The latter should be written as \code{from module import submod as s};
Thomas Wouters8bad6122000-08-19 20:55:02 +0000571see below.
572
Thomas Wouters52152252000-08-17 22:55:00 +0000573The \keyword{from} form does not bind the module name: it goes through the
574list of identifiers, looks each one of them up in the module found in step
575(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000576As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000577supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000578\exception{ImportError} is raised. If the list of identifiers is replaced
Thomas Wouters52152252000-08-17 22:55:00 +0000579by a star (\samp{*}), all names defined in the module are bound, except
580those beginning with an underscore (\character{_}).
Fred Drakef6669171998-05-06 19:52:49 +0000581\indexii{name}{binding}
582\exindex{ImportError}
583
Guido van Rossum56c20131998-07-24 18:25:38 +0000584Names bound by \keyword{import} statements may not occur in
585\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000586\stindex{global}
587
Fred Drake011f6fc1999-04-14 12:52:14 +0000588The \keyword{from} form with \samp{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000589\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000590\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000591
Fred Drake246837d1998-07-24 20:28:22 +0000592\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000593when the module names contains one or more dots, the module search
594path is carried out differently. The sequence of identifiers up to
595the last dot is used to find a ``package''\index{packages}; the final
596identifier is then searched inside the package. A package is
597generally a subdirectory of a directory on \code{sys.path} that has a
598file \file{__init__.py}.\ttindex{__init__.py}
599%
600[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000601\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000602about how the module search works from inside a package.]
603
604[XXX Also should mention __import__().]
605\bifuncindex{__import__}
606
Fred Drake2829f1c2001-06-23 05:27:20 +0000607
Fred Drake011f6fc1999-04-14 12:52:14 +0000608\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000609\stindex{global}
610
611\begin{verbatim}
612global_stmt: "global" identifier ("," identifier)*
613\end{verbatim}
614
615The \keyword{global} statement is a declaration which holds for the
616entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000617interpreted as globals. While \emph{using} global names is automatic
618if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000619names would be impossible without \keyword{global}.
620\indexiii{global}{name}{binding}
621
622Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000623code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000624
625Names listed in a \keyword{global} statement must not be defined as formal
626parameters or in a \keyword{for} loop control target, \keyword{class}
627definition, function definition, or \keyword{import} statement.
628
629(The current implementation does not enforce the latter two
630restrictions, but programs should not abuse this freedom, as future
631implementations may enforce them or silently change the meaning of the
632program.)
633
Guido van Rossum56c20131998-07-24 18:25:38 +0000634\strong{Programmer's note:}
635the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000636applies only to code parsed at the same time as the \keyword{global}
637statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000638\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000639the \keyword{exec} statement, and code contained in an \keyword{exec}
640statement is unaffected by \keyword{global} statements in the code
641containing the \keyword{exec} statement. The same applies to the
642\function{eval()}, \function{execfile()} and \function{compile()} functions.
643\stindex{exec}
644\bifuncindex{eval}
645\bifuncindex{execfile}
646\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000647
Fred Drake2829f1c2001-06-23 05:27:20 +0000648
Fred Drake011f6fc1999-04-14 12:52:14 +0000649\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000650\stindex{exec}
651
652\begin{verbatim}
653exec_stmt: "exec" expression ["in" expression ["," expression]]
654\end{verbatim}
655
656This statement supports dynamic execution of Python code. The first
657expression should evaluate to either a string, an open file object, or
658a code object. If it is a string, the string is parsed as a suite of
659Python statements which is then executed (unless a syntax error
Fred Drake93852ef2001-06-23 06:06:52 +0000660occurs). If it is an open file, the file is parsed until \EOF{} and
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000661executed. If it is a code object, it is simply executed.
662
663In all cases, if the optional parts are omitted, the code is executed
664in the current scope. If only the first expression after \keyword{in}
665is specified, it should be a dictionary, which will be used for both
666the global and the local variables. If two expressions are given,
667both must be dictionaries and they are used for the global and local
668variables, respectively.
669
670As a side effect, an implementation may insert additional keys into
671the dictionaries given besides those corresponding to variable names
672set by the executed code. For example, the current implementation
673may add a reference to the dictionary of the built-in module
674\module{__builtin__} under the key \code{__builtins__} (!).
675\ttindex{__builtins__}
676\refbimodindex{__builtin__}
677
Guido van Rossum56c20131998-07-24 18:25:38 +0000678\strong{Programmer's hints:}
679dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000680function \function{eval()}. The built-in functions
681\function{globals()} and \function{locals()} return the current global
682and local dictionary, respectively, which may be useful to pass around
683for use by \keyword{exec}.
684\bifuncindex{eval}
685\bifuncindex{globals}
686\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000687
688Also, in the current implementation, multi-line compound statements must
689end with a newline:
690\code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
691\code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
692\exception{SyntaxError}.
693\exindex{SyntaxError}
694
695