blob: 1fc885ed179546f16fa57746ed0169bbad66395c [file] [log] [blame]
Fred Drake011f6fc1999-04-14 12:52:14 +00001\chapter{Simple statements \label{simple}}
Fred Drakef6669171998-05-06 19:52:49 +00002\indexii{simple}{statement}
3
4Simple statements are comprised within a single logical line.
5Several simple statements may occur on a single line separated
6by semicolons. The syntax for simple statements is:
7
Fred Drakecb4638a2001-07-06 22:49:53 +00008\begin{productionlist}
Fred Drake53815882002-03-15 23:21:37 +00009 \production{simple_stmt}{\token{expression_stmt}}
10 \productioncont{| \token{assert_stmt}}
11 \productioncont{| \token{assignment_stmt}}
12 \productioncont{| \token{augmented_assignment_stmt}}
13 \productioncont{| \token{pass_stmt}}
14 \productioncont{| \token{del_stmt}}
15 \productioncont{| \token{print_stmt}}
16 \productioncont{| \token{return_stmt}}
17 \productioncont{| \token{yield_stmt}}
18 \productioncont{| \token{raise_stmt}}
19 \productioncont{| \token{break_stmt}}
20 \productioncont{| \token{continue_stmt}}
21 \productioncont{| \token{import_stmt}}
22 \productioncont{| \token{global_stmt}}
23 \productioncont{| \token{exec_stmt}}
Fred Drakecb4638a2001-07-06 22:49:53 +000024\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000025
Fred Drake2829f1c2001-06-23 05:27:20 +000026
Fred Drake011f6fc1999-04-14 12:52:14 +000027\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000028\indexii{expression}{statement}
29
30Expression statements are used (mostly interactively) to compute and
31write a value, or (usually) to call a procedure (a function that
32returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000033\code{None}). Other uses of expression statements are allowed and
34occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000035
Fred Drakecb4638a2001-07-06 22:49:53 +000036\begin{productionlist}
37 \production{expression_stmt}
38 {\token{expression_list}}
39\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000040
Guido van Rossum56c20131998-07-24 18:25:38 +000041An expression statement evaluates the expression list (which may be a
42single expression).
Fred Drakef6669171998-05-06 19:52:49 +000043\indexii{expression}{list}
44
45In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000046to a string using the built-in \function{repr()}\bifuncindex{repr}
47function and the resulting string is written to standard output (see
Fred Drakec2f496a2001-12-05 05:46:25 +000048section~\ref{print}) on a line by itself. (Expression statements
49yielding \code{None} are not written, so that procedure calls do not
50cause any output.)
Fred Drake7a700b82004-01-01 05:43:53 +000051\obindex{None}
Fred Drakef6669171998-05-06 19:52:49 +000052\indexii{string}{conversion}
53\index{output}
54\indexii{standard}{output}
55\indexii{writing}{values}
56\indexii{procedure}{call}
57
Fred Drake2829f1c2001-06-23 05:27:20 +000058
Fred Drake011f6fc1999-04-14 12:52:14 +000059\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000060
Fred Drake011f6fc1999-04-14 12:52:14 +000061Assert statements\stindex{assert} are a convenient way to insert
62debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000063
Fred Drakecb4638a2001-07-06 22:49:53 +000064\begin{productionlist}
Fred Drake007fadd2003-03-31 14:53:03 +000065 \production{assert_stmt}
Fred Drakecb4638a2001-07-06 22:49:53 +000066 {"assert" \token{expression} ["," \token{expression}]}
67\end{productionlist}
Guido van Rossum56c20131998-07-24 18:25:38 +000068
Fred Drake011f6fc1999-04-14 12:52:14 +000069The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000070
71\begin{verbatim}
72if __debug__:
73 if not expression: raise AssertionError
74\end{verbatim}
75
Fred Drake011f6fc1999-04-14 12:52:14 +000076The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000077equivalent to
78
79\begin{verbatim}
80if __debug__:
81 if not expression1: raise AssertionError, expression2
82\end{verbatim}
83
84These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000085\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000086variables with those names. In the current implementation, the
Johannes Gijsbersf4a70f32004-12-12 16:52:40 +000087built-in variable \code{__debug__} is \code{True} under normal
88circumstances, \code{False} when optimization is requested (command line
89option -O). The current code generator emits no code for an assert
90statement when optimization is requested at compile time. Note that it
91is unnecessary to include the source code for the expression that failed
92in the error message;
Guido van Rossum56c20131998-07-24 18:25:38 +000093it will be displayed as part of the stack trace.
94
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000095Assignments to \code{__debug__} are illegal. The value for the
96built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000097
Fred Drake2829f1c2001-06-23 05:27:20 +000098
Fred Drake011f6fc1999-04-14 12:52:14 +000099\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +0000100
Fred Drake011f6fc1999-04-14 12:52:14 +0000101Assignment statements\indexii{assignment}{statement} are used to
102(re)bind names to values and to modify attributes or items of mutable
103objects:
Fred Drakef6669171998-05-06 19:52:49 +0000104\indexii{binding}{name}
105\indexii{rebinding}{name}
106\obindex{mutable}
107\indexii{attribute}{assignment}
108
Fred Drakecb4638a2001-07-06 22:49:53 +0000109\begin{productionlist}
110 \production{assignment_stmt}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000111 {(\token{target_list} "=")+
112 (\token{expression_list} | \token{yield_expression})}
Fred Drakecb4638a2001-07-06 22:49:53 +0000113 \production{target_list}
114 {\token{target} ("," \token{target})* [","]}
115 \production{target}
Fred Drake53815882002-03-15 23:21:37 +0000116 {\token{identifier}}
117 \productioncont{| "(" \token{target_list} ")"}
118 \productioncont{| "[" \token{target_list} "]"}
119 \productioncont{| \token{attributeref}}
120 \productioncont{| \token{subscription}}
121 \productioncont{| \token{slicing}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000122\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000123
Fred Drakec2f496a2001-12-05 05:46:25 +0000124(See section~\ref{primaries} for the syntax definitions for the last
Fred Drakef6669171998-05-06 19:52:49 +0000125three symbols.)
126
127An assignment statement evaluates the expression list (remember that
128this can be a single expression or a comma-separated list, the latter
129yielding a tuple) and assigns the single resulting object to each of
130the target lists, from left to right.
131\indexii{expression}{list}
132
133Assignment is defined recursively depending on the form of the target
134(list). When a target is part of a mutable object (an attribute
135reference, subscription or slicing), the mutable object must
136ultimately perform the assignment and decide about its validity, and
137may raise an exception if the assignment is unacceptable. The rules
138observed by various types and the exceptions raised are given with the
Fred Drakec2f496a2001-12-05 05:46:25 +0000139definition of the object types (see section~\ref{types}).
Fred Drakef6669171998-05-06 19:52:49 +0000140\index{target}
141\indexii{target}{list}
142
143Assignment of an object to a target list is recursively defined as
144follows.
145\indexiii{target}{list}{assignment}
146
147\begin{itemize}
148\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000149If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000150target.
151
152\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000153If the target list is a comma-separated list of targets: The object
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000154must be a sequence with the same number of items as there are
Guido van Rossum56c20131998-07-24 18:25:38 +0000155targets in the target list, and the items are assigned, from left to
156right, to the corresponding targets. (This rule is relaxed as of
157Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000158strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000159now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000160
161\end{itemize}
162
163Assignment of an object to a single target is recursively defined as
164follows.
165
166\begin{itemize} % nested
167
168\item
169If the target is an identifier (name):
170
171\begin{itemize}
172
173\item
174If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000175code block: the name is bound to the object in the current local
176namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000177\stindex{global}
178
179\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000180Otherwise: the name is bound to the object in the current global
181namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000182
183\end{itemize} % nested
184
Guido van Rossum56c20131998-07-24 18:25:38 +0000185The name is rebound if it was already bound. This may cause the
186reference count for the object previously bound to the name to reach
187zero, causing the object to be deallocated and its
188destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000189
190\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000191If the target is a target list enclosed in parentheses or in square
192brackets: The object must be a sequence with the same number of items
193as there are targets in the target list, and its items are assigned,
194from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000195
196\item
197If the target is an attribute reference: The primary expression in the
198reference is evaluated. It should yield an object with assignable
199attributes; if this is not the case, \exception{TypeError} is raised. That
200object is then asked to assign the assigned object to the given
201attribute; if it cannot perform the assignment, it raises an exception
202(usually but not necessarily \exception{AttributeError}).
203\indexii{attribute}{assignment}
204
205\item
206If the target is a subscription: The primary expression in the
207reference is evaluated. It should yield either a mutable sequence
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000208object (such as a list) or a mapping object (such as a dictionary). Next,
Guido van Rossum56c20131998-07-24 18:25:38 +0000209the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000210\indexii{subscription}{assignment}
211\obindex{mutable}
212
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000213If the primary is a mutable sequence object (such as a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000214must yield a plain integer. If it is negative, the sequence's length
215is added to it. The resulting value must be a nonnegative integer
216less than the sequence's length, and the sequence is asked to assign
217the assigned object to its item with that index. If the index is out
218of range, \exception{IndexError} is raised (assignment to a subscripted
219sequence cannot add new items to a list).
220\obindex{sequence}
221\obindex{list}
222
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000223If the primary is a mapping object (such as a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000224have a type compatible with the mapping's key type, and the mapping is
225then asked to create a key/datum pair which maps the subscript to
226the assigned object. This can either replace an existing key/value
227pair with the same key value, or insert a new key/value pair (if no
228key with the same value existed).
229\obindex{mapping}
230\obindex{dictionary}
231
232\item
233If the target is a slicing: The primary expression in the reference is
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000234evaluated. It should yield a mutable sequence object (such as a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000235assigned object should be a sequence object of the same type. Next,
236the lower and upper bound expressions are evaluated, insofar they are
237present; defaults are zero and the sequence's length. The bounds
238should evaluate to (small) integers. If either bound is negative, the
239sequence's length is added to it. The resulting bounds are clipped to
240lie between zero and the sequence's length, inclusive. Finally, the
241sequence object is asked to replace the slice with the items of the
242assigned sequence. The length of the slice may be different from the
243length of the assigned sequence, thus changing the length of the
244target sequence, if the object allows it.
245\indexii{slicing}{assignment}
246
247\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000248
Fred Drakef6669171998-05-06 19:52:49 +0000249(In the current implementation, the syntax for targets is taken
250to be the same as for expressions, and invalid syntax is rejected
251during the code generation phase, causing less detailed error
252messages.)
253
254WARNING: Although the definition of assignment implies that overlaps
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000255between the left-hand side and the right-hand side are `safe' (for example
Fred Drake011f6fc1999-04-14 12:52:14 +0000256\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000257collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000258following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000259
260\begin{verbatim}
261x = [0, 1]
262i = 0
263i, x[i] = 1, 2
264print x
265\end{verbatim}
266
267
Fred Drake53815882002-03-15 23:21:37 +0000268\subsection{Augmented assignment statements \label{augassign}}
Fred Drake31f55502000-09-12 20:32:18 +0000269
270Augmented assignment is the combination, in a single statement, of a binary
271operation and an assignment statement:
272\indexii{augmented}{assignment}
273\index{statement!assignment, augmented}
274
Fred Drakecb4638a2001-07-06 22:49:53 +0000275\begin{productionlist}
276 \production{augmented_assignment_stmt}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000277 {\token{target} \token{augop}
278 (\token{expression_list} | \token{yield_expression})}
Fred Drakecb4638a2001-07-06 22:49:53 +0000279 \production{augop}
Fred Drake53815882002-03-15 23:21:37 +0000280 {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000281 \productioncont{| ">>=" | "<<=" | "\&=" | "\textasciicircum=" | "|="}
Fred Drakecb4638a2001-07-06 22:49:53 +0000282\end{productionlist}
Fred Drake31f55502000-09-12 20:32:18 +0000283
Fred Drakec2f496a2001-12-05 05:46:25 +0000284(See section~\ref{primaries} for the syntax definitions for the last
Fred Drake31f55502000-09-12 20:32:18 +0000285three symbols.)
286
Fred Draked68442b2000-09-21 22:01:36 +0000287An augmented assignment evaluates the target (which, unlike normal
288assignment statements, cannot be an unpacking) and the expression
289list, performs the binary operation specific to the type of assignment
290on the two operands, and assigns the result to the original
291target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000292
293An augmented assignment expression like \code{x += 1} can be rewritten as
294\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
295augmented version, \code{x} is only evaluated once. Also, when possible, the
296actual operation is performed \emph{in-place}, meaning that rather than
297creating a new object and assigning that to the target, the old object is
298modified instead.
299
300With the exception of assigning to tuples and multiple targets in a single
301statement, the assignment done by augmented assignment statements is handled
302the same way as normal assignments. Similarly, with the exception of the
Fred Drakec2f496a2001-12-05 05:46:25 +0000303possible \emph{in-place} behavior, the binary operation performed by
Fred Drake31f55502000-09-12 20:32:18 +0000304augmented assignment is the same as the normal binary operations.
305
Raymond Hettinger04e7e0c2002-06-25 13:36:41 +0000306For targets which are attribute references, the initial value is
307retrieved with a \method{getattr()} and the result is assigned with a
308\method{setattr()}. Notice that the two methods do not necessarily
309refer to the same variable. When \method{getattr()} refers to a class
310variable, \method{setattr()} still writes to an instance variable.
311For example:
312
313\begin{verbatim}
314class A:
315 x = 3 # class variable
316a = A()
317a.x += 1 # writes a.x as 4 leaving A.x as 3
318\end{verbatim}
319
Fred Drake31f55502000-09-12 20:32:18 +0000320
Fred Drake011f6fc1999-04-14 12:52:14 +0000321\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000322\stindex{pass}
323
Fred Drakecb4638a2001-07-06 22:49:53 +0000324\begin{productionlist}
325 \production{pass_stmt}
326 {"pass"}
327\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000328
329\keyword{pass} is a null operation --- when it is executed, nothing
330happens. It is useful as a placeholder when a statement is
331required syntactically, but no code needs to be executed, for example:
332\indexii{null}{operation}
333
334\begin{verbatim}
335def f(arg): pass # a function that does nothing (yet)
336
337class C: pass # a class with no methods (yet)
338\end{verbatim}
339
Fred Drake2829f1c2001-06-23 05:27:20 +0000340
Fred Drake011f6fc1999-04-14 12:52:14 +0000341\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000342\stindex{del}
343
Fred Drakecb4638a2001-07-06 22:49:53 +0000344\begin{productionlist}
345 \production{del_stmt}
346 {"del" \token{target_list}}
347\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000348
349Deletion is recursively defined very similar to the way assignment is
350defined. Rather that spelling it out in full details, here are some
351hints.
352\indexii{deletion}{target}
353\indexiii{deletion}{target}{list}
354
355Deletion of a target list recursively deletes each target, from left
356to right.
357
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000358Deletion of a name removes the binding of that name
Guido van Rossum56c20131998-07-24 18:25:38 +0000359from the local or global namespace, depending on whether the name
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000360occurs in a \keyword{global} statement in the same code block. If the
361name is unbound, a \exception{NameError} exception will be raised.
Fred Drakef6669171998-05-06 19:52:49 +0000362\stindex{global}
363\indexii{unbinding}{name}
364
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000365It is illegal to delete a name from the local namespace if it occurs
Michael W. Hudson495afea2002-06-17 12:51:57 +0000366as a free variable\indexii{free}{variable} in a nested block.
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000367
Fred Drakef6669171998-05-06 19:52:49 +0000368Deletion of attribute references, subscriptions and slicings
369is passed to the primary object involved; deletion of a slicing
370is in general equivalent to assignment of an empty slice of the
371right type (but even this is determined by the sliced object).
372\indexii{attribute}{deletion}
373
Fred Drake2829f1c2001-06-23 05:27:20 +0000374
Fred Drake011f6fc1999-04-14 12:52:14 +0000375\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000376\stindex{print}
377
Fred Drakecb4638a2001-07-06 22:49:53 +0000378\begin{productionlist}
379 \production{print_stmt}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000380 {"print" ([\token{expression} ("," \token{expression})* [","]}
Fred Drakef25fa6d2006-05-03 02:04:40 +0000381 \productioncont{| ">>" \token{expression}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000382 [("," \token{expression})+ [","])}
Fred Drakecb4638a2001-07-06 22:49:53 +0000383\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000384
Fred Draked4c33521998-10-01 20:39:47 +0000385\keyword{print} evaluates each expression in turn and writes the
386resulting object to standard output (see below). If an object is not
Fred Drakebe9d10e2001-06-23 06:16:52 +0000387a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000388conversions. The (resulting or original) string is then written. A
Fred Drakebe9d10e2001-06-23 06:16:52 +0000389space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000390the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000391line. This is the case (1) when no characters have yet been written
392to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000393output is \character{\e n}, or (3) when the last write operation on
394standard output was not a \keyword{print} statement. (In some cases
395it may be functional to write an empty string to standard output for
Fred Drakec2f496a2001-12-05 05:46:25 +0000396this reason.) \note{Objects which act like file objects but which are
397not the built-in file objects often do not properly emulate this
398aspect of the file object's behavior, so it is best not to rely on
399this.}
Fred Drakef6669171998-05-06 19:52:49 +0000400\index{output}
401\indexii{writing}{values}
402
Fred Draked4c33521998-10-01 20:39:47 +0000403A \character{\e n} character is written at the end, unless the
404\keyword{print} statement ends with a comma. This is the only action
405if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000406\indexii{trailing}{comma}
407\indexii{newline}{suppression}
408
Fred Drakedde91f01998-05-06 20:59:46 +0000409Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000410in the built-in module \module{sys}. If no such object exists, or if
411it does not have a \method{write()} method, a \exception{RuntimeError}
412exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000413\indexii{standard}{output}
414\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000415\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000416\exindex{RuntimeError}
417
Fred Drakecb4638a2001-07-06 22:49:53 +0000418\keyword{print} also has an extended\index{extended print statement}
419form, defined by the second portion of the syntax described above.
420This form is sometimes referred to as ``\keyword{print} chevron.''
Fred Drake2de7a352006-05-03 02:27:40 +0000421In this form, the first expression after the \code{>>} must
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000422evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000423\method{write()} method as described above. With this extended form,
424the subsequent expressions are printed to this file object. If the
425first expression evaluates to \code{None}, then \code{sys.stdout} is
426used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000427
Fred Drake2829f1c2001-06-23 05:27:20 +0000428
Fred Drake011f6fc1999-04-14 12:52:14 +0000429\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000430\stindex{return}
431
Fred Drakecb4638a2001-07-06 22:49:53 +0000432\begin{productionlist}
433 \production{return_stmt}
434 {"return" [\token{expression_list}]}
435\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000436
437\keyword{return} may only occur syntactically nested in a function
438definition, not within a nested class definition.
439\indexii{function}{definition}
440\indexii{class}{definition}
441
Guido van Rossum56c20131998-07-24 18:25:38 +0000442If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000443is substituted.
444
Guido van Rossum56c20131998-07-24 18:25:38 +0000445\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000446list (or \code{None}) as return value.
447
448When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000449with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000450before really leaving the function.
451\kwindex{finally}
452
Fred Drakee31e9ce2001-12-11 21:10:08 +0000453In a generator function, the \keyword{return} statement is not allowed
454to include an \grammartoken{expression_list}. In that context, a bare
455\keyword{return} indicates that the generator is done and will cause
456\exception{StopIteration} to be raised.
457
458
459\section{The \keyword{yield} statement \label{yield}}
460\stindex{yield}
461
462\begin{productionlist}
463 \production{yield_stmt}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000464 {\token{yield_expression}}
Fred Drakee31e9ce2001-12-11 21:10:08 +0000465\end{productionlist}
466
467\index{generator!function}
468\index{generator!iterator}
469\index{function!generator}
470\exindex{StopIteration}
471
472The \keyword{yield} statement is only used when defining a generator
473function, and is only used in the body of the generator function.
474Using a \keyword{yield} statement in a function definition is
475sufficient to cause that definition to create a generator function
476instead of a normal function.
477
478When a generator function is called, it returns an iterator known as a
479generator iterator, or more commonly, a generator. The body of the
480generator function is executed by calling the generator's
481\method{next()} method repeatedly until it raises an exception.
482
483When a \keyword{yield} statement is executed, the state of the
484generator is frozen and the value of \grammartoken{expression_list} is
485returned to \method{next()}'s caller. By ``frozen'' we mean that all
486local state is retained, including the current bindings of local
487variables, the instruction pointer, and the internal evaluation stack:
488enough information is saved so that the next time \method{next()} is
489invoked, the function can proceed exactly as if the \keyword{yield}
490statement were just another external call.
491
Phillip J. Eby1a9fac02006-03-25 00:46:43 +0000492As of Python version 2.5, the \keyword{yield} statement is now
493allowed in the \keyword{try} clause of a \keyword{try} ...\
494\keyword{finally} construct. If the generator is not resumed before
495it is finalized (by reaching a zero reference count or by being garbage
496collected), the generator-iterator's \method{close()} method will be
497called, allowing any pending \keyword{finally} clauses to execute.
Fred Drakee31e9ce2001-12-11 21:10:08 +0000498
Fred Drake08d752c2001-12-14 22:55:14 +0000499\begin{notice}
500In Python 2.2, the \keyword{yield} statement is only allowed
Fred Drake8d0645c2001-12-12 06:06:43 +0000501when the \code{generators} feature has been enabled. It will always
Raymond Hettinger68804312005-01-01 00:28:46 +0000502be enabled in Python 2.3. This \code{__future__} import statement can
Fred Drake08d752c2001-12-14 22:55:14 +0000503be used to enable the feature:
Fred Drake8d0645c2001-12-12 06:06:43 +0000504
505\begin{verbatim}
506from __future__ import generators
507\end{verbatim}
Fred Drake08d752c2001-12-14 22:55:14 +0000508\end{notice}
Fred Drake8d0645c2001-12-12 06:06:43 +0000509
510
Fred Drakee31e9ce2001-12-11 21:10:08 +0000511\begin{seealso}
512 \seepep{0255}{Simple Generators}
513 {The proposal for adding generators and the \keyword{yield}
514 statement to Python.}
Phillip J. Eby1a9fac02006-03-25 00:46:43 +0000515
516 \seepep{0342}{Coroutines via Enhanced Generators}
517 {The proposal that, among other generator enhancements,
518 proposed allowing \keyword{yield} to appear inside a
519 \keyword{try} ... \keyword{finally} block.}
Fred Drakee31e9ce2001-12-11 21:10:08 +0000520\end{seealso}
521
Fred Drake2829f1c2001-06-23 05:27:20 +0000522
Fred Drake011f6fc1999-04-14 12:52:14 +0000523\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000524\stindex{raise}
525
Fred Drakecb4638a2001-07-06 22:49:53 +0000526\begin{productionlist}
527 \production{raise_stmt}
528 {"raise" [\token{expression} ["," \token{expression}
529 ["," \token{expression}]]]}
530\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000531
Guido van Rossum56c20131998-07-24 18:25:38 +0000532If no expressions are present, \keyword{raise} re-raises the last
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000533exception that was active in the current scope. If no exception is
Raymond Hettingerbee0d462005-10-03 16:39:51 +0000534active in the current scope, a \exception{TypeError} exception is
535raised indicating that this is an error (if running under IDLE, a
Neal Norwitzc0d11252005-10-04 03:43:43 +0000536\exception{Queue.Empty} exception is raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000537\index{exception}
538\indexii{raising}{exception}
539
Fred Drake81932e22002-06-20 20:55:29 +0000540Otherwise, \keyword{raise} evaluates the expressions to get three
541objects, using \code{None} as the value of omitted expressions. The
542first two objects are used to determine the \emph{type} and
543\emph{value} of the exception.
Fred Drakef6669171998-05-06 19:52:49 +0000544
Fred Drake81932e22002-06-20 20:55:29 +0000545If the first object is an instance, the type of the exception is the
Fred Drake8bd62af2003-01-25 03:47:35 +0000546class of the instance, the instance itself is the value, and the
Fred Drake81932e22002-06-20 20:55:29 +0000547second object must be \code{None}.
548
549If the first object is a class, it becomes the type of the exception.
550The second object is used to determine the exception value: If it is
551an instance of the class, the instance becomes the exception value.
552If the second object is a tuple, it is used as the argument list for
553the class constructor; if it is \code{None}, an empty argument list is
554used, and any other object is treated as a single argument to the
555constructor. The instance so created by calling the constructor is
556used as the exception value.
557
Fred Drake81932e22002-06-20 20:55:29 +0000558If a third object is present and not \code{None}, it must be a
559traceback\obindex{traceback} object (see section~\ref{traceback}), and
560it is substituted instead of the current location as the place where
561the exception occurred. If the third object is present and not a
562traceback object or \code{None}, a \exception{TypeError} exception is
563raised. The three-expression form of \keyword{raise} is useful to
564re-raise an exception transparently in an except clause, but
565\keyword{raise} with no expressions should be preferred if the
566exception to be re-raised was the most recently active exception in
567the current scope.
568
Fred Drakee7097e02002-10-18 15:18:18 +0000569Additional information on exceptions can be found in
570section~\ref{exceptions}, and information about handling exceptions is
571in section~\ref{try}.
Fred Drakef6669171998-05-06 19:52:49 +0000572
Fred Drake2829f1c2001-06-23 05:27:20 +0000573
Fred Drake011f6fc1999-04-14 12:52:14 +0000574\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000575\stindex{break}
576
Fred Drakecb4638a2001-07-06 22:49:53 +0000577\begin{productionlist}
578 \production{break_stmt}
579 {"break"}
580\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000581
582\keyword{break} may only occur syntactically nested in a \keyword{for}
583or \keyword{while} loop, but not nested in a function or class definition
584within that loop.
585\stindex{for}
586\stindex{while}
587\indexii{loop}{statement}
588
589It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000590\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000591\kwindex{else}
592
593If a \keyword{for} loop is terminated by \keyword{break}, the loop control
594target keeps its current value.
595\indexii{loop control}{target}
596
597When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000598with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000599before really leaving the loop.
600\kwindex{finally}
601
Fred Drake2829f1c2001-06-23 05:27:20 +0000602
Fred Drake011f6fc1999-04-14 12:52:14 +0000603\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000604\stindex{continue}
605
Fred Drakecb4638a2001-07-06 22:49:53 +0000606\begin{productionlist}
607 \production{continue_stmt}
608 {"continue"}
609\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000610
611\keyword{continue} may only occur syntactically nested in a \keyword{for} or
612\keyword{while} loop, but not nested in a function or class definition or
Neal Norwitz19f6b862005-10-04 03:37:29 +0000613\keyword{finally} statement within that loop.\footnote{It may
Guido van Rossum56c20131998-07-24 18:25:38 +0000614occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000615restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000616laziness and will eventually be lifted.}
617It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000618\stindex{for}
619\stindex{while}
620\indexii{loop}{statement}
621\kwindex{finally}
622
Fred Drake2829f1c2001-06-23 05:27:20 +0000623
Fred Drake011f6fc1999-04-14 12:52:14 +0000624\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000625\stindex{import}
Fred Drakeb3be52e2003-07-15 21:37:58 +0000626\index{module!importing}
627\indexii{name}{binding}
628\kwindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000629
Fred Drakecb4638a2001-07-06 22:49:53 +0000630\begin{productionlist}
631 \production{import_stmt}
632 {"import" \token{module} ["as" \token{name}]
Fred Drake53815882002-03-15 23:21:37 +0000633 ( "," \token{module} ["as" \token{name}] )*}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000634 \productioncont{| "from" \token{relative_module} "import" \token{identifier}
Fred Drake53815882002-03-15 23:21:37 +0000635 ["as" \token{name}]}
636 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )*}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000637 \productioncont{| "from" \token{relative_module} "import" "("
638 \token{identifier} ["as" \token{name}]}
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000639 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )* [","] ")"}
Fred Drake53815882002-03-15 23:21:37 +0000640 \productioncont{| "from" \token{module} "import" "*"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000641 \production{module}
642 {(\token{identifier} ".")* \token{identifier}}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000643 \production{relative_module}
644 {"."* \token{module} | "."+}
645 \production{name}
646 {\token{identifier}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000647\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000648
649Import statements are executed in two steps: (1) find a module, and
650initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000651namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000652The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000653identifier in the list. The form with \keyword{from} performs step
654(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000655
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000656In this context, to ``initialize'' a built-in or extension module means to
657call an initialization function that the module must provide for the purpose
658(in the reference implementation, the function's name is obtained by
659prepending string ``init'' to the module's name); to ``initialize'' a
660Python-coded module means to execute the module's body.
661
662The system maintains a table of modules that have been or are being
663initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000664indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000665accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000666this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000667definition is started. When a module is found, it is loaded. Details
668of the module searching and loading process are implementation and
669platform specific. It generally involves searching for a ``built-in''
670module with the given name and then searching a list of locations
671given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000672\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000673\ttindex{sys.modules}
674\indexii{module}{name}
675\indexii{built-in}{module}
676\indexii{user-defined}{module}
677\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000678\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000679\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000680
Fred Draked51ce7d2003-07-15 22:03:00 +0000681If a built-in module is found,\indexii{module}{initialization} its
682built-in initialization code is executed and step (1) is finished. If
683no matching file is found,
684\exception{ImportError}\exindex{ImportError} is raised.
685\index{code block}If a file is found, it is parsed,
Fred Drakef6669171998-05-06 19:52:49 +0000686yielding an executable code block. If a syntax error occurs,
Fred Draked51ce7d2003-07-15 22:03:00 +0000687\exception{SyntaxError}\exindex{SyntaxError} is raised. Otherwise, an
688empty module of the given name is created and inserted in the module
689table, and then the code block is executed in the context of this
690module. Exceptions during this execution terminate step (1).
Fred Drakef6669171998-05-06 19:52:49 +0000691
692When step (1) finishes without raising an exception, step (2) can
693begin.
694
Fred Drake859eb622001-03-06 07:34:00 +0000695The first form of \keyword{import} statement binds the module name in
696the local namespace to the module object, and then goes on to import
697the next identifier, if any. If the module name is followed by
698\keyword{as}, the name following \keyword{as} is used as the local
Martin v. Löwis13dd9d92003-01-16 11:30:08 +0000699name for the module.
Thomas Wouters8bad6122000-08-19 20:55:02 +0000700
Thomas Wouters52152252000-08-17 22:55:00 +0000701The \keyword{from} form does not bind the module name: it goes through the
702list of identifiers, looks each one of them up in the module found in step
703(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000704As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000705supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000706\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drake08fd5152001-10-24 19:50:31 +0000707by a star (\character{*}), all public names defined in the module are
708bound in the local namespace of the \keyword{import} statement..
Fred Drakef6669171998-05-06 19:52:49 +0000709\indexii{name}{binding}
710\exindex{ImportError}
711
Fred Drake08fd5152001-10-24 19:50:31 +0000712The \emph{public names} defined by a module are determined by checking
713the module's namespace for a variable named \code{__all__}; if
714defined, it must be a sequence of strings which are names defined or
715imported by that module. The names given in \code{__all__} are all
716considered public and are required to exist. If \code{__all__} is not
717defined, the set of public names includes all names found in the
718module's namespace which do not begin with an underscore character
Raymond Hettinger1772f172003-01-06 12:54:54 +0000719(\character{_}). \code{__all__} should contain the entire public API.
720It is intended to avoid accidentally exporting items that are not part
721of the API (such as library modules which were imported and used within
722the module).
Fred Drake27cae1f2002-12-07 16:00:00 +0000723\withsubitem{(optional module attribute)}{\ttindex{__all__}}
Fred Drake08fd5152001-10-24 19:50:31 +0000724
Jeremy Hyltonf0c1f1b2002-04-01 21:19:44 +0000725The \keyword{from} form with \samp{*} may only occur in a module
726scope. If the wild card form of import --- \samp{import *} --- is
727used in a function and the function contains or is a nested block with
728free variables, the compiler will raise a \exception{SyntaxError}.
729
Fred Drakef6669171998-05-06 19:52:49 +0000730\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000731\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000732
Fred Drake246837d1998-07-24 20:28:22 +0000733\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000734when the module names contains one or more dots, the module search
735path is carried out differently. The sequence of identifiers up to
736the last dot is used to find a ``package''\index{packages}; the final
737identifier is then searched inside the package. A package is
738generally a subdirectory of a directory on \code{sys.path} that has a
739file \file{__init__.py}.\ttindex{__init__.py}
740%
741[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000742\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000743about how the module search works from inside a package.]
744
Fred Drake08fd5152001-10-24 19:50:31 +0000745The built-in function \function{__import__()} is provided to support
746applications that determine which modules need to be loaded
747dynamically; refer to \ulink{Built-in
748Functions}{../lib/built-in-funcs.html} in the
749\citetitle[../lib/lib.html]{Python Library Reference} for additional
750information.
Guido van Rossum56c20131998-07-24 18:25:38 +0000751\bifuncindex{__import__}
752
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000753\subsection{Future statements \label{future}}
754
755A \dfn{future statement}\indexii{future}{statement} is a directive to
756the compiler that a particular module should be compiled using syntax
757or semantics that will be available in a specified future release of
758Python. The future statement is intended to ease migration to future
759versions of Python that introduce incompatible changes to the
760language. It allows use of the new features on a per-module basis
761before the release in which the feature becomes standard.
762
763\begin{productionlist}[*]
764 \production{future_statement}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000765 {"from" "__future__" "import" feature ["as" name]}
766 \productioncont{ ("," feature ["as" name])*}
767 \productioncont{| "from" "__future__" "import" "(" feature ["as" name]}
768 \productioncont{ ("," feature ["as" name])* [","] ")"}
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000769 \production{feature}{identifier}
770 \production{name}{identifier}
771\end{productionlist}
772
773A future statement must appear near the top of the module. The only
774lines that can appear before a future statement are:
775
776\begin{itemize}
777
778\item the module docstring (if any),
779\item comments,
780\item blank lines, and
781\item other future statements.
782
783\end{itemize}
784
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000785The features recognized by Python 2.5 are \samp{absolute_import},
786\samp{division}, \samp{generators}, \samp{nested_scopes} and
787\samp{with_statement}. \samp{generators} and \samp{nested_scopes}
788are redundant in Python version 2.3 and above because they are always
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000789enabled.
790
791A future statement is recognized and treated specially at compile
792time: Changes to the semantics of core constructs are often
793implemented by generating different code. It may even be the case
794that a new feature introduces new incompatible syntax (such as a new
795reserved word), in which case the compiler may need to parse the
796module differently. Such decisions cannot be pushed off until
797runtime.
798
799For any given release, the compiler knows which feature names have been
800defined, and raises a compile-time error if a future statement contains
801a feature not known to it.
802
803The direct runtime semantics are the same as for any import statement:
804there is a standard module \module{__future__}, described later, and
805it will be imported in the usual way at the time the future statement
806is executed.
807
808The interesting runtime semantics depend on the specific feature
809enabled by the future statement.
810
811Note that there is nothing special about the statement:
812
813\begin{verbatim}
814import __future__ [as name]
815\end{verbatim}
816
817That is not a future statement; it's an ordinary import statement with
818no special semantics or syntax restrictions.
819
George Yoshida6fffa5e2006-05-20 15:36:19 +0000820Code compiled by an \keyword{exec} statement or calls to the builtin functions
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000821\function{compile()} and \function{execfile()} that occur in a module
822\module{M} containing a future statement will, by default, use the new
823syntax or semantics associated with the future statement. This can,
824starting with Python 2.2 be controlled by optional arguments to
George Yoshida6fffa5e2006-05-20 15:36:19 +0000825\function{compile()} --- see the documentation of that function in the
826\citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
827details.
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000828
829A future statement typed at an interactive interpreter prompt will
830take effect for the rest of the interpreter session. If an
831interpreter is started with the \programopt{-i} option, is passed a
832script name to execute, and the script includes a future statement, it
833will be in effect in the interactive session started after the script
834is executed.
Fred Drake2829f1c2001-06-23 05:27:20 +0000835
Fred Drake011f6fc1999-04-14 12:52:14 +0000836\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000837\stindex{global}
838
Fred Drakecb4638a2001-07-06 22:49:53 +0000839\begin{productionlist}
840 \production{global_stmt}
841 {"global" \token{identifier} ("," \token{identifier})*}
842\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000843
844The \keyword{global} statement is a declaration which holds for the
845entire current code block. It means that the listed identifiers are to be
Jeremy Hyltonf3255c82002-04-01 21:25:32 +0000846interpreted as globals. It would be impossible to assign to a global
847variable without \keyword{global}, although free variables may refer
848to globals without being declared global.
Fred Drakef6669171998-05-06 19:52:49 +0000849\indexiii{global}{name}{binding}
850
851Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000852code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000853
854Names listed in a \keyword{global} statement must not be defined as formal
855parameters or in a \keyword{for} loop control target, \keyword{class}
856definition, function definition, or \keyword{import} statement.
857
858(The current implementation does not enforce the latter two
859restrictions, but programs should not abuse this freedom, as future
860implementations may enforce them or silently change the meaning of the
861program.)
862
Guido van Rossum56c20131998-07-24 18:25:38 +0000863\strong{Programmer's note:}
864the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000865applies only to code parsed at the same time as the \keyword{global}
866statement. In particular, a \keyword{global} statement contained in an
Fred Drakedde91f01998-05-06 20:59:46 +0000867\keyword{exec} statement does not affect the code block \emph{containing}
Fred Drakef6669171998-05-06 19:52:49 +0000868the \keyword{exec} statement, and code contained in an \keyword{exec}
869statement is unaffected by \keyword{global} statements in the code
870containing the \keyword{exec} statement. The same applies to the
871\function{eval()}, \function{execfile()} and \function{compile()} functions.
872\stindex{exec}
873\bifuncindex{eval}
874\bifuncindex{execfile}
875\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000876
Fred Drake2829f1c2001-06-23 05:27:20 +0000877
Fred Drake011f6fc1999-04-14 12:52:14 +0000878\section{The \keyword{exec} statement \label{exec}}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000879\stindex{exec}
880
Fred Drakecb4638a2001-07-06 22:49:53 +0000881\begin{productionlist}
882 \production{exec_stmt}
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000883 {"exec" \token{or_expr}
Fred Drakecb4638a2001-07-06 22:49:53 +0000884 ["in" \token{expression} ["," \token{expression}]]}
885\end{productionlist}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000886
887This statement supports dynamic execution of Python code. The first
888expression should evaluate to either a string, an open file object, or
889a code object. If it is a string, the string is parsed as a suite of
890Python statements which is then executed (unless a syntax error
Fred Drake93852ef2001-06-23 06:06:52 +0000891occurs). If it is an open file, the file is parsed until \EOF{} and
Fred Drakeb6e1c112005-09-07 05:17:07 +0000892executed. If it is a code object, it is simply executed. In all
Fredrik Lundh5a49fae2006-02-02 21:58:55 +0000893cases, the code that's executed is expected to be valid as file
Fred Drakeb6e1c112005-09-07 05:17:07 +0000894input (see section~\ref{file-input}, ``File input''). Be aware that
895the \keyword{return} and \keyword{yield} statements may not be used
896outside of function definitions even within the context of code passed
897to the \keyword{exec} statement.
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000898
899In all cases, if the optional parts are omitted, the code is executed
900in the current scope. If only the first expression after \keyword{in}
901is specified, it should be a dictionary, which will be used for both
902the global and the local variables. If two expressions are given,
Raymond Hettinger70fcdb82004-08-03 05:17:58 +0000903they are used for the global and local variables, respectively.
904If provided, \var{locals} can be any mapping object.
905\versionchanged[formerly \var{locals} was required to be a dictionary]{2.4}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000906
907As a side effect, an implementation may insert additional keys into
908the dictionaries given besides those corresponding to variable names
909set by the executed code. For example, the current implementation
910may add a reference to the dictionary of the built-in module
911\module{__builtin__} under the key \code{__builtins__} (!).
912\ttindex{__builtins__}
913\refbimodindex{__builtin__}
914
Guido van Rossum56c20131998-07-24 18:25:38 +0000915\strong{Programmer's hints:}
916dynamic evaluation of expressions is supported by the built-in
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000917function \function{eval()}. The built-in functions
918\function{globals()} and \function{locals()} return the current global
919and local dictionary, respectively, which may be useful to pass around
920for use by \keyword{exec}.
921\bifuncindex{eval}
922\bifuncindex{globals}
923\bifuncindex{locals}
Greg Ward38c28e32000-04-27 18:32:02 +0000924
Greg Ward38c28e32000-04-27 18:32:02 +0000925
926
Žiga Seilnachtc64ad482007-03-24 14:24:26 +0000927
928