blob: 7212071338d23449a15f15e92fd4c1fef7ddc98d [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 Drake011f6fc1999-04-14 12:52:14 +000025\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000026\indexii{expression}{statement}
27
28Expression statements are used (mostly interactively) to compute and
29write a value, or (usually) to call a procedure (a function that
30returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000031\code{None}). Other uses of expression statements are allowed and
32occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000033
34\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +000035expression_stmt: expression_list
Fred Drakef6669171998-05-06 19:52:49 +000036\end{verbatim}
37
Guido van Rossum56c20131998-07-24 18:25:38 +000038An expression statement evaluates the expression list (which may be a
39single expression).
Fred Drakef6669171998-05-06 19:52:49 +000040\indexii{expression}{list}
41
42In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000043to a string using the built-in \function{repr()}\bifuncindex{repr}
44function and the resulting string is written to standard output (see
45section \ref{print}) on a line by itself. (Expression statements
46yielding None are not written, so that procedure calls do not cause
47any output.)
Fred Drakef6669171998-05-06 19:52:49 +000048\ttindex{None}
49\indexii{string}{conversion}
50\index{output}
51\indexii{standard}{output}
52\indexii{writing}{values}
53\indexii{procedure}{call}
54
Fred Drake011f6fc1999-04-14 12:52:14 +000055\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000056
Fred Drake011f6fc1999-04-14 12:52:14 +000057Assert statements\stindex{assert} are a convenient way to insert
58debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000059
60\begin{verbatim}
61assert_statement: "assert" expression ["," expression]
62\end{verbatim}
63
Fred Drake011f6fc1999-04-14 12:52:14 +000064The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000065
66\begin{verbatim}
67if __debug__:
68 if not expression: raise AssertionError
69\end{verbatim}
70
Fred Drake011f6fc1999-04-14 12:52:14 +000071The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000072equivalent to
73
74\begin{verbatim}
75if __debug__:
76 if not expression1: raise AssertionError, expression2
77\end{verbatim}
78
79These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000080\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000081variables with those names. In the current implementation, the
82built-in variable \code{__debug__} is 1 under normal circumstances, 0
83when optimization is requested (command line option -O). The current
84code generator emits no code for an assert statement when optimization
85is requested at compile time. Note that it is unnecessary to include
86the source code for the expression that failed in the error message;
87it will be displayed as part of the stack trace.
88
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000089Assignments to \code{__debug__} are illegal. The value for the
90built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000091
Fred Drake011f6fc1999-04-14 12:52:14 +000092\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000093
Fred Drake011f6fc1999-04-14 12:52:14 +000094Assignment statements\indexii{assignment}{statement} are used to
95(re)bind names to values and to modify attributes or items of mutable
96objects:
Fred Drakef6669171998-05-06 19:52:49 +000097\indexii{binding}{name}
98\indexii{rebinding}{name}
99\obindex{mutable}
100\indexii{attribute}{assignment}
101
102\begin{verbatim}
103assignment_stmt: (target_list "=")+ expression_list
104target_list: target ("," target)* [","]
105target: identifier | "(" target_list ")" | "[" target_list "]"
106 | attributeref | subscription | slicing
107\end{verbatim}
108
109(See section \ref{primaries} for the syntax definitions for the last
110three symbols.)
111
112An assignment statement evaluates the expression list (remember that
113this can be a single expression or a comma-separated list, the latter
114yielding a tuple) and assigns the single resulting object to each of
115the target lists, from left to right.
116\indexii{expression}{list}
117
118Assignment is defined recursively depending on the form of the target
119(list). When a target is part of a mutable object (an attribute
120reference, subscription or slicing), the mutable object must
121ultimately perform the assignment and decide about its validity, and
122may raise an exception if the assignment is unacceptable. The rules
123observed by various types and the exceptions raised are given with the
124definition of the object types (see section \ref{types}).
125\index{target}
126\indexii{target}{list}
127
128Assignment of an object to a target list is recursively defined as
129follows.
130\indexiii{target}{list}{assignment}
131
132\begin{itemize}
133\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000134If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000135target.
136
137\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000138If the target list is a comma-separated list of targets: The object
139must be a sequence with the same number of items as the there are
140targets in the target list, and the items are assigned, from left to
141right, to the corresponding targets. (This rule is relaxed as of
142Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000143strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000144now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000145
146\end{itemize}
147
148Assignment of an object to a single target is recursively defined as
149follows.
150
151\begin{itemize} % nested
152
153\item
154If the target is an identifier (name):
155
156\begin{itemize}
157
158\item
159If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000160code block: the name is bound to the object in the current local
161namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000162\stindex{global}
163
164\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000165Otherwise: the name is bound to the object in the current global
166namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000167
168\end{itemize} % nested
169
Guido van Rossum56c20131998-07-24 18:25:38 +0000170The name is rebound if it was already bound. This may cause the
171reference count for the object previously bound to the name to reach
172zero, causing the object to be deallocated and its
173destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000174
175\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000176If the target is a target list enclosed in parentheses or in square
177brackets: The object must be a sequence with the same number of items
178as there are targets in the target list, and its items are assigned,
179from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000180
181\item
182If the target is an attribute reference: The primary expression in the
183reference is evaluated. It should yield an object with assignable
184attributes; if this is not the case, \exception{TypeError} is raised. That
185object is then asked to assign the assigned object to the given
186attribute; if it cannot perform the assignment, it raises an exception
187(usually but not necessarily \exception{AttributeError}).
188\indexii{attribute}{assignment}
189
190\item
191If the target is a subscription: The primary expression in the
192reference is evaluated. It should yield either a mutable sequence
Guido van Rossum56c20131998-07-24 18:25:38 +0000193object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
194the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000195\indexii{subscription}{assignment}
196\obindex{mutable}
197
Guido van Rossum56c20131998-07-24 18:25:38 +0000198If the primary is a mutable sequence object (e.g., a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000199must yield a plain integer. If it is negative, the sequence's length
200is added to it. The resulting value must be a nonnegative integer
201less than the sequence's length, and the sequence is asked to assign
202the assigned object to its item with that index. If the index is out
203of range, \exception{IndexError} is raised (assignment to a subscripted
204sequence cannot add new items to a list).
205\obindex{sequence}
206\obindex{list}
207
Guido van Rossum56c20131998-07-24 18:25:38 +0000208If the primary is a mapping object (e.g., a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000209have a type compatible with the mapping's key type, and the mapping is
210then asked to create a key/datum pair which maps the subscript to
211the assigned object. This can either replace an existing key/value
212pair with the same key value, or insert a new key/value pair (if no
213key with the same value existed).
214\obindex{mapping}
215\obindex{dictionary}
216
217\item
218If the target is a slicing: The primary expression in the reference is
Guido van Rossum56c20131998-07-24 18:25:38 +0000219evaluated. It should yield a mutable sequence object (e.g., a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000220assigned object should be a sequence object of the same type. Next,
221the lower and upper bound expressions are evaluated, insofar they are
222present; defaults are zero and the sequence's length. The bounds
223should evaluate to (small) integers. If either bound is negative, the
224sequence's length is added to it. The resulting bounds are clipped to
225lie between zero and the sequence's length, inclusive. Finally, the
226sequence object is asked to replace the slice with the items of the
227assigned sequence. The length of the slice may be different from the
228length of the assigned sequence, thus changing the length of the
229target sequence, if the object allows it.
230\indexii{slicing}{assignment}
231
232\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000233
Fred Drakef6669171998-05-06 19:52:49 +0000234(In the current implementation, the syntax for targets is taken
235to be the same as for expressions, and invalid syntax is rejected
236during the code generation phase, causing less detailed error
237messages.)
238
239WARNING: Although the definition of assignment implies that overlaps
Guido van Rossum56c20131998-07-24 18:25:38 +0000240between the left-hand side and the right-hand side are `safe' (e.g.,
Fred Drake011f6fc1999-04-14 12:52:14 +0000241\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000242collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000243following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000244
245\begin{verbatim}
246x = [0, 1]
247i = 0
248i, x[i] = 1, 2
249print x
250\end{verbatim}
251
252
Fred Drake31f55502000-09-12 20:32:18 +0000253\subsection{Augmented Assignment statements \label{augassign}}
254
255Augmented assignment is the combination, in a single statement, of a binary
256operation and an assignment statement:
257\indexii{augmented}{assignment}
258\index{statement!assignment, augmented}
259
260\begin{verbatim}
261augmented_assignment_stmt: target augop expression_list
262augop: "+=" | "-=" | "*=" | "/=" | "%=" | "**="
263 | ">>=" | "<<=" | "&=" | "^=" | "|="
264target: identifier | "(" target_list ")" | "[" target_list "]"
265 | attributeref | subscription | slicing
266\end{verbatim}
267
268(See section \ref{primaries} for the syntax definitions for the last
269three symbols.)
270
Fred Draked68442b2000-09-21 22:01:36 +0000271An augmented assignment evaluates the target (which, unlike normal
272assignment statements, cannot be an unpacking) and the expression
273list, performs the binary operation specific to the type of assignment
274on the two operands, and assigns the result to the original
275target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000276
277An augmented assignment expression like \code{x += 1} can be rewritten as
278\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
279augmented version, \code{x} is only evaluated once. Also, when possible, the
280actual operation is performed \emph{in-place}, meaning that rather than
281creating a new object and assigning that to the target, the old object is
282modified instead.
283
284With the exception of assigning to tuples and multiple targets in a single
285statement, the assignment done by augmented assignment statements is handled
286the same way as normal assignments. Similarly, with the exception of the
287possible \emph{in-place} behaviour, the binary operation performed by
288augmented assignment is the same as the normal binary operations.
289
290
Fred Drake011f6fc1999-04-14 12:52:14 +0000291\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000292\stindex{pass}
293
294\begin{verbatim}
295pass_stmt: "pass"
296\end{verbatim}
297
298\keyword{pass} is a null operation --- when it is executed, nothing
299happens. It is useful as a placeholder when a statement is
300required syntactically, but no code needs to be executed, for example:
301\indexii{null}{operation}
302
303\begin{verbatim}
304def f(arg): pass # a function that does nothing (yet)
305
306class C: pass # a class with no methods (yet)
307\end{verbatim}
308
Fred Drake011f6fc1999-04-14 12:52:14 +0000309\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000310\stindex{del}
311
312\begin{verbatim}
313del_stmt: "del" target_list
314\end{verbatim}
315
316Deletion is recursively defined very similar to the way assignment is
317defined. Rather that spelling it out in full details, here are some
318hints.
319\indexii{deletion}{target}
320\indexiii{deletion}{target}{list}
321
322Deletion of a target list recursively deletes each target, from left
323to right.
324
325Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum56c20131998-07-24 18:25:38 +0000326from the local or global namespace, depending on whether the name
Fred Drakef6669171998-05-06 19:52:49 +0000327occurs in a \keyword{global} statement in the same code block.
328\stindex{global}
329\indexii{unbinding}{name}
330
331Deletion of attribute references, subscriptions and slicings
332is passed to the primary object involved; deletion of a slicing
333is in general equivalent to assignment of an empty slice of the
334right type (but even this is determined by the sliced object).
335\indexii{attribute}{deletion}
336
Fred Drake011f6fc1999-04-14 12:52:14 +0000337\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000338\stindex{print}
339
340\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000341print_stmt: "print" [ expression ("," expression)* [","] ]
Fred Drakef6669171998-05-06 19:52:49 +0000342\end{verbatim}
343
Fred Draked4c33521998-10-01 20:39:47 +0000344\keyword{print} evaluates each expression in turn and writes the
345resulting object to standard output (see below). If an object is not
346a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000347conversions. The (resulting or original) string is then written. A
Fred Draked4c33521998-10-01 20:39:47 +0000348space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000349the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000350line. This is the case (1) when no characters have yet been written
351to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000352output is \character{\e n}, or (3) when the last write operation on
353standard output was not a \keyword{print} statement. (In some cases
354it may be functional to write an empty string to standard output for
355this reason.)
Fred Drakef6669171998-05-06 19:52:49 +0000356\index{output}
357\indexii{writing}{values}
358
Fred Draked4c33521998-10-01 20:39:47 +0000359A \character{\e n} character is written at the end, unless the
360\keyword{print} statement ends with a comma. This is the only action
361if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000362\indexii{trailing}{comma}
363\indexii{newline}{suppression}
364
Fred Drakedde91f01998-05-06 20:59:46 +0000365Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000366in the built-in module \module{sys}. If no such object exists, or if
367it does not have a \method{write()} method, a \exception{RuntimeError}
368exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000369\indexii{standard}{output}
370\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000371\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000372\exindex{RuntimeError}
373
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000374\keyword{print} also has an extended form, defined as
Fred Draked68442b2000-09-21 22:01:36 +0000375\index{extended print statement}
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000376
377\begin{verbatim}
Fred Draked68442b2000-09-21 22:01:36 +0000378print_stmt: "print" ">>" expression [ ("," expression)+ [","] ]
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000379\end{verbatim}
380
381In this form, the first expression after the \keyword{>>} must
382evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000383\method{write()} method as described above. With this extended form,
384the subsequent expressions are printed to this file object. If the
385first expression evaluates to \code{None}, then \code{sys.stdout} is
386used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000387
Fred Drake011f6fc1999-04-14 12:52:14 +0000388\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000389\stindex{return}
390
391\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000392return_stmt: "return" [expression_list]
Fred Drakef6669171998-05-06 19:52:49 +0000393\end{verbatim}
394
395\keyword{return} may only occur syntactically nested in a function
396definition, not within a nested class definition.
397\indexii{function}{definition}
398\indexii{class}{definition}
399
Guido van Rossum56c20131998-07-24 18:25:38 +0000400If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000401is substituted.
402
Guido van Rossum56c20131998-07-24 18:25:38 +0000403\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000404list (or \code{None}) as return value.
405
406When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000407with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000408before really leaving the function.
409\kwindex{finally}
410
Fred Drake011f6fc1999-04-14 12:52:14 +0000411\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000412\stindex{raise}
413
414\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000415raise_stmt: "raise" [expression ["," expression ["," expression]]]
Fred Drakef6669171998-05-06 19:52:49 +0000416\end{verbatim}
417
Guido van Rossum56c20131998-07-24 18:25:38 +0000418If no expressions are present, \keyword{raise} re-raises the last
419expression that was raised in the current scope.
420
Fred Drake011f6fc1999-04-14 12:52:14 +0000421Otherwise, \keyword{raise} evaluates its first expression, which must yield
Guido van Rossum56c20131998-07-24 18:25:38 +0000422a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000423this is evaluated, else \code{None} is substituted. If the first
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000424expression is a class object, then the second expression may be an
425instance of that class or one of its derivatives, and then that
426instance is raised. If the second expression is not such an instance,
427the given class is instantiated. The argument list for the
428instantiation is determined as follows: if the second expression is a
429tuple, it is used as the argument list; if it is \code{None}, the
430argument list is empty; otherwise, the argument list consists of a
431single argument which is the second expression. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000432expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000433\code{None}.
434\index{exception}
435\indexii{raising}{exception}
436
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000437If the first object is a string, it then raises the exception
Fred Drakef6669171998-05-06 19:52:49 +0000438identified by the first object, with the second one (or \code{None})
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000439as its parameter. If the first object is a class or instance,
440it raises the exception identified by the class of the instance
441determined in the previous step, with the instance as
442its parameter.
Fred Drakef6669171998-05-06 19:52:49 +0000443
Guido van Rossum56c20131998-07-24 18:25:38 +0000444If a third object is present, and it is not \code{None}, it should be
Fred Drakef6669171998-05-06 19:52:49 +0000445a traceback object (see section \ref{traceback}), and it is
446substituted instead of the current location as the place where the
447exception occurred. This is useful to re-raise an exception
448transparently in an except clause.
449\obindex{traceback}
450
Fred Drake011f6fc1999-04-14 12:52:14 +0000451\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000452\stindex{break}
453
454\begin{verbatim}
455break_stmt: "break"
456\end{verbatim}
457
458\keyword{break} may only occur syntactically nested in a \keyword{for}
459or \keyword{while} loop, but not nested in a function or class definition
460within that loop.
461\stindex{for}
462\stindex{while}
463\indexii{loop}{statement}
464
465It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000466\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000467\kwindex{else}
468
469If a \keyword{for} loop is terminated by \keyword{break}, the loop control
470target keeps its current value.
471\indexii{loop control}{target}
472
473When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000474with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000475before really leaving the loop.
476\kwindex{finally}
477
Fred Drake011f6fc1999-04-14 12:52:14 +0000478\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000479\stindex{continue}
480
481\begin{verbatim}
482continue_stmt: "continue"
483\end{verbatim}
484
485\keyword{continue} may only occur syntactically nested in a \keyword{for} or
486\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000487\keyword{try} statement within that loop.\footnote{It may
488occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000489restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000490laziness and will eventually be lifted.}
491It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000492\stindex{for}
493\stindex{while}
494\indexii{loop}{statement}
495\kwindex{finally}
496
Fred Drake011f6fc1999-04-14 12:52:14 +0000497\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000498\stindex{import}
499
500\begin{verbatim}
Thomas Wouters52152252000-08-17 22:55:00 +0000501import_stmt: "import" module ["as" name] ("," module ["as" name] )*
502 | "from" module "import" identifier ["as" name]
503 ("," identifier ["as" name] )*
Guido van Rossum56c20131998-07-24 18:25:38 +0000504 | "from" module "import" "*"
505module: (identifier ".")* identifier
Fred Drakef6669171998-05-06 19:52:49 +0000506\end{verbatim}
507
508Import statements are executed in two steps: (1) find a module, and
509initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000510namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000511The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000512identifier in the list. The form with \keyword{from} performs step
513(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000514\indexii{importing}{module}
515\indexii{name}{binding}
516\kwindex{from}
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000517% XXX Need to define what ``initialize'' means here
Fred Drakef6669171998-05-06 19:52:49 +0000518
519The system maintains a table of modules that have been initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000520indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000521accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000522this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000523definition is started. When a module is found, it is loaded. Details
524of the module searching and loading process are implementation and
525platform specific. It generally involves searching for a ``built-in''
526module with the given name and then searching a list of locations
527given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000528\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000529\ttindex{sys.modules}
530\indexii{module}{name}
531\indexii{built-in}{module}
532\indexii{user-defined}{module}
533\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000534\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000535\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000536
537If a built-in module is found, its built-in initialization code is
538executed and step (1) is finished. If no matching file is found,
539\exception{ImportError} is raised. If a file is found, it is parsed,
540yielding an executable code block. If a syntax error occurs,
541\exception{SyntaxError} is raised. Otherwise, an empty module of the given
542name is created and inserted in the module table, and then the code
543block is executed in the context of this module. Exceptions during
544this execution terminate step (1).
545\indexii{module}{initialization}
546\exindex{SyntaxError}
547\exindex{ImportError}
548\index{code block}
549
550When step (1) finishes without raising an exception, step (2) can
551begin.
552
Fred Drake859eb622001-03-06 07:34:00 +0000553The first form of \keyword{import} statement binds the module name in
554the local namespace to the module object, and then goes on to import
555the next identifier, if any. If the module name is followed by
556\keyword{as}, the name following \keyword{as} is used as the local
557name for the module. To avoid confusion, you cannot import modules
558with dotted names \keyword{as} a different local name. So \code{import
559module as m} is legal, but \code{import module.submod as s} is not.
560The latter should be written as \code{from module import submod as s};
Thomas Wouters8bad6122000-08-19 20:55:02 +0000561see below.
562
Thomas Wouters52152252000-08-17 22:55:00 +0000563The \keyword{from} form does not bind the module name: it goes through the
564list of identifiers, looks each one of them up in the module found in step
565(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000566As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000567supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000568\exception{ImportError} is raised. If the list of identifiers is replaced
Thomas Wouters52152252000-08-17 22:55:00 +0000569by a star (\samp{*}), all names defined in the module are bound, except
570those beginning with an underscore (\character{_}).
Fred Drakef6669171998-05-06 19:52:49 +0000571\indexii{name}{binding}
572\exindex{ImportError}
573
Guido van Rossum56c20131998-07-24 18:25:38 +0000574Names bound by \keyword{import} statements may not occur in
575\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000576\stindex{global}
577
Fred Drake011f6fc1999-04-14 12:52:14 +0000578The \keyword{from} form with \samp{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000579\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000580\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000581
Fred Drake246837d1998-07-24 20:28:22 +0000582\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000583when the module names contains one or more dots, the module search
584path is carried out differently. The sequence of identifiers up to
585the last dot is used to find a ``package''\index{packages}; the final
586identifier is then searched inside the package. A package is
587generally a subdirectory of a directory on \code{sys.path} that has a
588file \file{__init__.py}.\ttindex{__init__.py}
589%
590[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000591\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000592about how the module search works from inside a package.]
593
594[XXX Also should mention __import__().]
595\bifuncindex{__import__}
596
Fred Drake011f6fc1999-04-14 12:52:14 +0000597\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000598\stindex{global}
599
600\begin{verbatim}
601global_stmt: "global" identifier ("," identifier)*
602\end{verbatim}
603
604The \keyword{global} statement is a declaration which holds for the
605entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000606interpreted as globals. While \emph{using} global names is automatic
607if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000608names would be impossible without \keyword{global}.
609\indexiii{global}{name}{binding}
610
611Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000612code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000613
614Names listed in a \keyword{global} statement must not be defined as formal
615parameters or in a \keyword{for} loop control target, \keyword{class}
616definition, function definition, or \keyword{import} statement.
617
618(The current implementation does not enforce the latter two
619restrictions, but programs should not abuse this freedom, as future
620implementations may enforce them or silently change the meaning of the
621program.)
622
Guido van Rossum56c20131998-07-24 18:25:38 +0000623\strong{Programmer's note:}
624the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000625applies only to code parsed at the same time as the \keyword{global}
626statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000627\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000628the \keyword{exec} statement, and code contained in an \keyword{exec}
629statement is unaffected by \keyword{global} statements in the code
630containing the \keyword{exec} statement. The same applies to the
631\function{eval()}, \function{execfile()} and \function{compile()} functions.
632\stindex{exec}
633\bifuncindex{eval}
634\bifuncindex{execfile}
635\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000636
Fred Drake011f6fc1999-04-14 12:52:14 +0000637\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000638\stindex{exec}
639
640\begin{verbatim}
641exec_stmt: "exec" expression ["in" expression ["," expression]]
642\end{verbatim}
643
644This statement supports dynamic execution of Python code. The first
645expression should evaluate to either a string, an open file object, or
646a code object. If it is a string, the string is parsed as a suite of
647Python statements which is then executed (unless a syntax error
648occurs). If it is an open file, the file is parsed until EOF and
649executed. If it is a code object, it is simply executed.
650
651In all cases, if the optional parts are omitted, the code is executed
652in the current scope. If only the first expression after \keyword{in}
653is specified, it should be a dictionary, which will be used for both
654the global and the local variables. If two expressions are given,
655both must be dictionaries and they are used for the global and local
656variables, respectively.
657
658As a side effect, an implementation may insert additional keys into
659the dictionaries given besides those corresponding to variable names
660set by the executed code. For example, the current implementation
661may add a reference to the dictionary of the built-in module
662\module{__builtin__} under the key \code{__builtins__} (!).
663\ttindex{__builtins__}
664\refbimodindex{__builtin__}
665
Guido van Rossum56c20131998-07-24 18:25:38 +0000666\strong{Programmer's hints:}
667dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000668function \function{eval()}. The built-in functions
669\function{globals()} and \function{locals()} return the current global
670and local dictionary, respectively, which may be useful to pass around
671for use by \keyword{exec}.
672\bifuncindex{eval}
673\bifuncindex{globals}
674\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000675
676Also, in the current implementation, multi-line compound statements must
677end with a newline:
678\code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
679\code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
680\exception{SyntaxError}.
681\exindex{SyntaxError}
682
683