blob: d61165f8fcc4da0cee5c012dacb75fa2913af89a [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
89
Fred Drake011f6fc1999-04-14 12:52:14 +000090\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000091
Fred Drake011f6fc1999-04-14 12:52:14 +000092Assignment statements\indexii{assignment}{statement} are used to
93(re)bind names to values and to modify attributes or items of mutable
94objects:
Fred Drakef6669171998-05-06 19:52:49 +000095\indexii{binding}{name}
96\indexii{rebinding}{name}
97\obindex{mutable}
98\indexii{attribute}{assignment}
99
100\begin{verbatim}
101assignment_stmt: (target_list "=")+ expression_list
102target_list: target ("," target)* [","]
103target: identifier | "(" target_list ")" | "[" target_list "]"
104 | attributeref | subscription | slicing
105\end{verbatim}
106
107(See section \ref{primaries} for the syntax definitions for the last
108three symbols.)
109
110An assignment statement evaluates the expression list (remember that
111this can be a single expression or a comma-separated list, the latter
112yielding a tuple) and assigns the single resulting object to each of
113the target lists, from left to right.
114\indexii{expression}{list}
115
116Assignment is defined recursively depending on the form of the target
117(list). When a target is part of a mutable object (an attribute
118reference, subscription or slicing), the mutable object must
119ultimately perform the assignment and decide about its validity, and
120may raise an exception if the assignment is unacceptable. The rules
121observed by various types and the exceptions raised are given with the
122definition of the object types (see section \ref{types}).
123\index{target}
124\indexii{target}{list}
125
126Assignment of an object to a target list is recursively defined as
127follows.
128\indexiii{target}{list}{assignment}
129
130\begin{itemize}
131\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000132If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000133target.
134
135\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000136If the target list is a comma-separated list of targets: The object
137must be a sequence with the same number of items as the there are
138targets in the target list, and the items are assigned, from left to
139right, to the corresponding targets. (This rule is relaxed as of
140Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000141strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000142now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000143
144\end{itemize}
145
146Assignment of an object to a single target is recursively defined as
147follows.
148
149\begin{itemize} % nested
150
151\item
152If the target is an identifier (name):
153
154\begin{itemize}
155
156\item
157If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000158code block: the name is bound to the object in the current local
159namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000160\stindex{global}
161
162\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000163Otherwise: the name is bound to the object in the current global
164namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000165
166\end{itemize} % nested
167
Guido van Rossum56c20131998-07-24 18:25:38 +0000168The name is rebound if it was already bound. This may cause the
169reference count for the object previously bound to the name to reach
170zero, causing the object to be deallocated and its
171destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000172
173\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000174If the target is a target list enclosed in parentheses or in square
175brackets: The object must be a sequence with the same number of items
176as there are targets in the target list, and its items are assigned,
177from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000178
179\item
180If the target is an attribute reference: The primary expression in the
181reference is evaluated. It should yield an object with assignable
182attributes; if this is not the case, \exception{TypeError} is raised. That
183object is then asked to assign the assigned object to the given
184attribute; if it cannot perform the assignment, it raises an exception
185(usually but not necessarily \exception{AttributeError}).
186\indexii{attribute}{assignment}
187
188\item
189If the target is a subscription: The primary expression in the
190reference is evaluated. It should yield either a mutable sequence
Guido van Rossum56c20131998-07-24 18:25:38 +0000191object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
192the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000193\indexii{subscription}{assignment}
194\obindex{mutable}
195
Guido van Rossum56c20131998-07-24 18:25:38 +0000196If the primary is a mutable sequence object (e.g., a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000197must yield a plain integer. If it is negative, the sequence's length
198is added to it. The resulting value must be a nonnegative integer
199less than the sequence's length, and the sequence is asked to assign
200the assigned object to its item with that index. If the index is out
201of range, \exception{IndexError} is raised (assignment to a subscripted
202sequence cannot add new items to a list).
203\obindex{sequence}
204\obindex{list}
205
Guido van Rossum56c20131998-07-24 18:25:38 +0000206If the primary is a mapping object (e.g., a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000207have a type compatible with the mapping's key type, and the mapping is
208then asked to create a key/datum pair which maps the subscript to
209the assigned object. This can either replace an existing key/value
210pair with the same key value, or insert a new key/value pair (if no
211key with the same value existed).
212\obindex{mapping}
213\obindex{dictionary}
214
215\item
216If the target is a slicing: The primary expression in the reference is
Guido van Rossum56c20131998-07-24 18:25:38 +0000217evaluated. It should yield a mutable sequence object (e.g., a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000218assigned object should be a sequence object of the same type. Next,
219the lower and upper bound expressions are evaluated, insofar they are
220present; defaults are zero and the sequence's length. The bounds
221should evaluate to (small) integers. If either bound is negative, the
222sequence's length is added to it. The resulting bounds are clipped to
223lie between zero and the sequence's length, inclusive. Finally, the
224sequence object is asked to replace the slice with the items of the
225assigned sequence. The length of the slice may be different from the
226length of the assigned sequence, thus changing the length of the
227target sequence, if the object allows it.
228\indexii{slicing}{assignment}
229
230\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000231
Fred Drakef6669171998-05-06 19:52:49 +0000232(In the current implementation, the syntax for targets is taken
233to be the same as for expressions, and invalid syntax is rejected
234during the code generation phase, causing less detailed error
235messages.)
236
237WARNING: Although the definition of assignment implies that overlaps
Guido van Rossum56c20131998-07-24 18:25:38 +0000238between the left-hand side and the right-hand side are `safe' (e.g.,
Fred Drake011f6fc1999-04-14 12:52:14 +0000239\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000240collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000241following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000242
243\begin{verbatim}
244x = [0, 1]
245i = 0
246i, x[i] = 1, 2
247print x
248\end{verbatim}
249
250
Fred Drake31f55502000-09-12 20:32:18 +0000251\subsection{Augmented Assignment statements \label{augassign}}
252
253Augmented assignment is the combination, in a single statement, of a binary
254operation and an assignment statement:
255\indexii{augmented}{assignment}
256\index{statement!assignment, augmented}
257
258\begin{verbatim}
259augmented_assignment_stmt: target augop expression_list
260augop: "+=" | "-=" | "*=" | "/=" | "%=" | "**="
261 | ">>=" | "<<=" | "&=" | "^=" | "|="
262target: identifier | "(" target_list ")" | "[" target_list "]"
263 | attributeref | subscription | slicing
264\end{verbatim}
265
266(See section \ref{primaries} for the syntax definitions for the last
267three symbols.)
268
Fred Draked68442b2000-09-21 22:01:36 +0000269An augmented assignment evaluates the target (which, unlike normal
270assignment statements, cannot be an unpacking) and the expression
271list, performs the binary operation specific to the type of assignment
272on the two operands, and assigns the result to the original
273target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000274
275An augmented assignment expression like \code{x += 1} can be rewritten as
276\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
277augmented version, \code{x} is only evaluated once. Also, when possible, the
278actual operation is performed \emph{in-place}, meaning that rather than
279creating a new object and assigning that to the target, the old object is
280modified instead.
281
282With the exception of assigning to tuples and multiple targets in a single
283statement, the assignment done by augmented assignment statements is handled
284the same way as normal assignments. Similarly, with the exception of the
285possible \emph{in-place} behaviour, the binary operation performed by
286augmented assignment is the same as the normal binary operations.
287
288
Fred Drake011f6fc1999-04-14 12:52:14 +0000289\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000290\stindex{pass}
291
292\begin{verbatim}
293pass_stmt: "pass"
294\end{verbatim}
295
296\keyword{pass} is a null operation --- when it is executed, nothing
297happens. It is useful as a placeholder when a statement is
298required syntactically, but no code needs to be executed, for example:
299\indexii{null}{operation}
300
301\begin{verbatim}
302def f(arg): pass # a function that does nothing (yet)
303
304class C: pass # a class with no methods (yet)
305\end{verbatim}
306
Fred Drake011f6fc1999-04-14 12:52:14 +0000307\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000308\stindex{del}
309
310\begin{verbatim}
311del_stmt: "del" target_list
312\end{verbatim}
313
314Deletion is recursively defined very similar to the way assignment is
315defined. Rather that spelling it out in full details, here are some
316hints.
317\indexii{deletion}{target}
318\indexiii{deletion}{target}{list}
319
320Deletion of a target list recursively deletes each target, from left
321to right.
322
323Deletion of a name removes the binding of that name (which must exist)
Guido van Rossum56c20131998-07-24 18:25:38 +0000324from the local or global namespace, depending on whether the name
Fred Drakef6669171998-05-06 19:52:49 +0000325occurs in a \keyword{global} statement in the same code block.
326\stindex{global}
327\indexii{unbinding}{name}
328
329Deletion of attribute references, subscriptions and slicings
330is passed to the primary object involved; deletion of a slicing
331is in general equivalent to assignment of an empty slice of the
332right type (but even this is determined by the sliced object).
333\indexii{attribute}{deletion}
334
Fred Drake011f6fc1999-04-14 12:52:14 +0000335\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000336\stindex{print}
337
338\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000339print_stmt: "print" [ expression ("," expression)* [","] ]
Fred Drakef6669171998-05-06 19:52:49 +0000340\end{verbatim}
341
Fred Draked4c33521998-10-01 20:39:47 +0000342\keyword{print} evaluates each expression in turn and writes the
343resulting object to standard output (see below). If an object is not
344a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000345conversions. The (resulting or original) string is then written. A
Fred Draked4c33521998-10-01 20:39:47 +0000346space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000347the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000348line. This is the case (1) when no characters have yet been written
349to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000350output is \character{\e n}, or (3) when the last write operation on
351standard output was not a \keyword{print} statement. (In some cases
352it may be functional to write an empty string to standard output for
353this reason.)
Fred Drakef6669171998-05-06 19:52:49 +0000354\index{output}
355\indexii{writing}{values}
356
Fred Draked4c33521998-10-01 20:39:47 +0000357A \character{\e n} character is written at the end, unless the
358\keyword{print} statement ends with a comma. This is the only action
359if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000360\indexii{trailing}{comma}
361\indexii{newline}{suppression}
362
Fred Drakedde91f01998-05-06 20:59:46 +0000363Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000364in the built-in module \module{sys}. If no such object exists, or if
365it does not have a \method{write()} method, a \exception{RuntimeError}
366exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000367\indexii{standard}{output}
368\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000369\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000370\exindex{RuntimeError}
371
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000372\keyword{print} also has an extended form, defined as
Fred Draked68442b2000-09-21 22:01:36 +0000373\index{extended print statement}
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000374
375\begin{verbatim}
Fred Draked68442b2000-09-21 22:01:36 +0000376print_stmt: "print" ">>" expression [ ("," expression)+ [","] ]
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000377\end{verbatim}
378
379In this form, the first expression after the \keyword{>>} must
380evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000381\method{write()} method as described above. With this extended form,
382the subsequent expressions are printed to this file object. If the
383first expression evaluates to \code{None}, then \code{sys.stdout} is
384used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000385
Fred Drake011f6fc1999-04-14 12:52:14 +0000386\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000387\stindex{return}
388
389\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000390return_stmt: "return" [expression_list]
Fred Drakef6669171998-05-06 19:52:49 +0000391\end{verbatim}
392
393\keyword{return} may only occur syntactically nested in a function
394definition, not within a nested class definition.
395\indexii{function}{definition}
396\indexii{class}{definition}
397
Guido van Rossum56c20131998-07-24 18:25:38 +0000398If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000399is substituted.
400
Guido van Rossum56c20131998-07-24 18:25:38 +0000401\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000402list (or \code{None}) as return value.
403
404When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000405with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000406before really leaving the function.
407\kwindex{finally}
408
Fred Drake011f6fc1999-04-14 12:52:14 +0000409\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000410\stindex{raise}
411
412\begin{verbatim}
Guido van Rossum56c20131998-07-24 18:25:38 +0000413raise_stmt: "raise" [expression ["," expression ["," expression]]]
Fred Drakef6669171998-05-06 19:52:49 +0000414\end{verbatim}
415
Guido van Rossum56c20131998-07-24 18:25:38 +0000416If no expressions are present, \keyword{raise} re-raises the last
417expression that was raised in the current scope.
418
Fred Drake011f6fc1999-04-14 12:52:14 +0000419Otherwise, \keyword{raise} evaluates its first expression, which must yield
Guido van Rossum56c20131998-07-24 18:25:38 +0000420a string, class, or instance object. If there is a second expression,
Fred Drakef6669171998-05-06 19:52:49 +0000421this is evaluated, else \code{None} is substituted. If the first
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000422expression is a class object, then the second expression may be an
423instance of that class or one of its derivatives, and then that
424instance is raised. If the second expression is not such an instance,
425the given class is instantiated. The argument list for the
426instantiation is determined as follows: if the second expression is a
427tuple, it is used as the argument list; if it is \code{None}, the
428argument list is empty; otherwise, the argument list consists of a
429single argument which is the second expression. If the first
Guido van Rossum56c20131998-07-24 18:25:38 +0000430expression is an instance object, the second expression must be
Fred Drakef6669171998-05-06 19:52:49 +0000431\code{None}.
432\index{exception}
433\indexii{raising}{exception}
434
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000435If the first object is a string, it then raises the exception
Fred Drakef6669171998-05-06 19:52:49 +0000436identified by the first object, with the second one (or \code{None})
Guido van Rossumf5a80a41998-08-25 14:45:41 +0000437as its parameter. If the first object is a class or instance,
438it raises the exception identified by the class of the instance
439determined in the previous step, with the instance as
440its parameter.
Fred Drakef6669171998-05-06 19:52:49 +0000441
Guido van Rossum56c20131998-07-24 18:25:38 +0000442If a third object is present, and it is not \code{None}, it should be
Fred Drakef6669171998-05-06 19:52:49 +0000443a traceback object (see section \ref{traceback}), and it is
444substituted instead of the current location as the place where the
445exception occurred. This is useful to re-raise an exception
446transparently in an except clause.
447\obindex{traceback}
448
Fred Drake011f6fc1999-04-14 12:52:14 +0000449\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000450\stindex{break}
451
452\begin{verbatim}
453break_stmt: "break"
454\end{verbatim}
455
456\keyword{break} may only occur syntactically nested in a \keyword{for}
457or \keyword{while} loop, but not nested in a function or class definition
458within that loop.
459\stindex{for}
460\stindex{while}
461\indexii{loop}{statement}
462
463It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000464\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000465\kwindex{else}
466
467If a \keyword{for} loop is terminated by \keyword{break}, the loop control
468target keeps its current value.
469\indexii{loop control}{target}
470
471When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000472with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000473before really leaving the loop.
474\kwindex{finally}
475
Fred Drake011f6fc1999-04-14 12:52:14 +0000476\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000477\stindex{continue}
478
479\begin{verbatim}
480continue_stmt: "continue"
481\end{verbatim}
482
483\keyword{continue} may only occur syntactically nested in a \keyword{for} or
484\keyword{while} loop, but not nested in a function or class definition or
Guido van Rossum56c20131998-07-24 18:25:38 +0000485\keyword{try} statement within that loop.\footnote{It may
486occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000487restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000488laziness and will eventually be lifted.}
489It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000490\stindex{for}
491\stindex{while}
492\indexii{loop}{statement}
493\kwindex{finally}
494
Fred Drake011f6fc1999-04-14 12:52:14 +0000495\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000496\stindex{import}
497
498\begin{verbatim}
Thomas Wouters52152252000-08-17 22:55:00 +0000499import_stmt: "import" module ["as" name] ("," module ["as" name] )*
500 | "from" module "import" identifier ["as" name]
501 ("," identifier ["as" name] )*
Guido van Rossum56c20131998-07-24 18:25:38 +0000502 | "from" module "import" "*"
503module: (identifier ".")* identifier
Fred Drakef6669171998-05-06 19:52:49 +0000504\end{verbatim}
505
506Import statements are executed in two steps: (1) find a module, and
507initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000508namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000509The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000510identifier in the list. The form with \keyword{from} performs step
511(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000512\indexii{importing}{module}
513\indexii{name}{binding}
514\kwindex{from}
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000515% XXX Need to define what ``initialize'' means here
Fred Drakef6669171998-05-06 19:52:49 +0000516
517The system maintains a table of modules that have been initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000518indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000519accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000520this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000521definition is started. When a module is found, it is loaded. Details
522of the module searching and loading process are implementation and
523platform specific. It generally involves searching for a ``built-in''
524module with the given name and then searching a list of locations
525given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000526\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000527\ttindex{sys.modules}
528\indexii{module}{name}
529\indexii{built-in}{module}
530\indexii{user-defined}{module}
531\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000532\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000533\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000534
535If a built-in module is found, its built-in initialization code is
536executed and step (1) is finished. If no matching file is found,
537\exception{ImportError} is raised. If a file is found, it is parsed,
538yielding an executable code block. If a syntax error occurs,
539\exception{SyntaxError} is raised. Otherwise, an empty module of the given
540name is created and inserted in the module table, and then the code
541block is executed in the context of this module. Exceptions during
542this execution terminate step (1).
543\indexii{module}{initialization}
544\exindex{SyntaxError}
545\exindex{ImportError}
546\index{code block}
547
548When step (1) finishes without raising an exception, step (2) can
549begin.
550
Fred Drake859eb622001-03-06 07:34:00 +0000551The first form of \keyword{import} statement binds the module name in
552the local namespace to the module object, and then goes on to import
553the next identifier, if any. If the module name is followed by
554\keyword{as}, the name following \keyword{as} is used as the local
555name for the module. To avoid confusion, you cannot import modules
556with dotted names \keyword{as} a different local name. So \code{import
557module as m} is legal, but \code{import module.submod as s} is not.
558The latter should be written as \code{from module import submod as s};
Thomas Wouters8bad6122000-08-19 20:55:02 +0000559see below.
560
Thomas Wouters52152252000-08-17 22:55:00 +0000561The \keyword{from} form does not bind the module name: it goes through the
562list of identifiers, looks each one of them up in the module found in step
563(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000564As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000565supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000566\exception{ImportError} is raised. If the list of identifiers is replaced
Thomas Wouters52152252000-08-17 22:55:00 +0000567by a star (\samp{*}), all names defined in the module are bound, except
568those beginning with an underscore (\character{_}).
Fred Drakef6669171998-05-06 19:52:49 +0000569\indexii{name}{binding}
570\exindex{ImportError}
571
Guido van Rossum56c20131998-07-24 18:25:38 +0000572Names bound by \keyword{import} statements may not occur in
573\keyword{global} statements in the same scope.
Fred Drakef6669171998-05-06 19:52:49 +0000574\stindex{global}
575
Fred Drake011f6fc1999-04-14 12:52:14 +0000576The \keyword{from} form with \samp{*} may only occur in a module scope.
Fred Drakef6669171998-05-06 19:52:49 +0000577\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000578\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000579
Fred Drake246837d1998-07-24 20:28:22 +0000580\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000581when the module names contains one or more dots, the module search
582path is carried out differently. The sequence of identifiers up to
583the last dot is used to find a ``package''\index{packages}; the final
584identifier is then searched inside the package. A package is
585generally a subdirectory of a directory on \code{sys.path} that has a
586file \file{__init__.py}.\ttindex{__init__.py}
587%
588[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000589\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000590about how the module search works from inside a package.]
591
592[XXX Also should mention __import__().]
593\bifuncindex{__import__}
594
Fred Drake011f6fc1999-04-14 12:52:14 +0000595\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000596\stindex{global}
597
598\begin{verbatim}
599global_stmt: "global" identifier ("," identifier)*
600\end{verbatim}
601
602The \keyword{global} statement is a declaration which holds for the
603entire current code block. It means that the listed identifiers are to be
Fred Drakedde91f01998-05-06 20:59:46 +0000604interpreted as globals. While \emph{using} global names is automatic
605if they are not defined in the local scope, \emph{assigning} to global
Fred Drakef6669171998-05-06 19:52:49 +0000606names would be impossible without \keyword{global}.
607\indexiii{global}{name}{binding}
608
609Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000610code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000611
612Names listed in a \keyword{global} statement must not be defined as formal
613parameters or in a \keyword{for} loop control target, \keyword{class}
614definition, function definition, or \keyword{import} statement.
615
616(The current implementation does not enforce the latter two
617restrictions, but programs should not abuse this freedom, as future
618implementations may enforce them or silently change the meaning of the
619program.)
620
Guido van Rossum56c20131998-07-24 18:25:38 +0000621\strong{Programmer's note:}
622the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000623applies only to code parsed at the same time as the \keyword{global}
624statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000625\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000626the \keyword{exec} statement, and code contained in an \keyword{exec}
627statement is unaffected by \keyword{global} statements in the code
628containing the \keyword{exec} statement. The same applies to the
629\function{eval()}, \function{execfile()} and \function{compile()} functions.
630\stindex{exec}
631\bifuncindex{eval}
632\bifuncindex{execfile}
633\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000634
Fred Drake011f6fc1999-04-14 12:52:14 +0000635\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000636\stindex{exec}
637
638\begin{verbatim}
639exec_stmt: "exec" expression ["in" expression ["," expression]]
640\end{verbatim}
641
642This statement supports dynamic execution of Python code. The first
643expression should evaluate to either a string, an open file object, or
644a code object. If it is a string, the string is parsed as a suite of
645Python statements which is then executed (unless a syntax error
646occurs). If it is an open file, the file is parsed until EOF and
647executed. If it is a code object, it is simply executed.
648
649In all cases, if the optional parts are omitted, the code is executed
650in the current scope. If only the first expression after \keyword{in}
651is specified, it should be a dictionary, which will be used for both
652the global and the local variables. If two expressions are given,
653both must be dictionaries and they are used for the global and local
654variables, respectively.
655
656As a side effect, an implementation may insert additional keys into
657the dictionaries given besides those corresponding to variable names
658set by the executed code. For example, the current implementation
659may add a reference to the dictionary of the built-in module
660\module{__builtin__} under the key \code{__builtins__} (!).
661\ttindex{__builtins__}
662\refbimodindex{__builtin__}
663
Guido van Rossum56c20131998-07-24 18:25:38 +0000664\strong{Programmer's hints:}
665dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000666function \function{eval()}. The built-in functions
667\function{globals()} and \function{locals()} return the current global
668and local dictionary, respectively, which may be useful to pass around
669for use by \keyword{exec}.
670\bifuncindex{eval}
671\bifuncindex{globals}
672\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000673
674Also, in the current implementation, multi-line compound statements must
675end with a newline:
676\code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
677\code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
678\exception{SyntaxError}.
679\exindex{SyntaxError}
680
681