blob: c1bbd9b4389db439cf1b64b1d78ede07b3a700c5 [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}}
Fred Drakecb4638a2001-07-06 22:49:53 +000023\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000024
Fred Drake2829f1c2001-06-23 05:27:20 +000025
Fred Drake011f6fc1999-04-14 12:52:14 +000026\section{Expression statements \label{exprstmts}}
Fred Drakef6669171998-05-06 19:52:49 +000027\indexii{expression}{statement}
28
29Expression statements are used (mostly interactively) to compute and
30write a value, or (usually) to call a procedure (a function that
31returns no meaningful result; in Python, procedures return the value
Guido van Rossum56c20131998-07-24 18:25:38 +000032\code{None}). Other uses of expression statements are allowed and
33occasionally useful. The syntax for an expression statement is:
Fred Drakef6669171998-05-06 19:52:49 +000034
Fred Drakecb4638a2001-07-06 22:49:53 +000035\begin{productionlist}
36 \production{expression_stmt}
37 {\token{expression_list}}
38\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000039
Guido van Rossum56c20131998-07-24 18:25:38 +000040An expression statement evaluates the expression list (which may be a
41single expression).
Fred Drakef6669171998-05-06 19:52:49 +000042\indexii{expression}{list}
43
44In interactive mode, if the value is not \code{None}, it is converted
Guido van Rossum56c20131998-07-24 18:25:38 +000045to a string using the built-in \function{repr()}\bifuncindex{repr}
46function and the resulting string is written to standard output (see
Fred Drakec2f496a2001-12-05 05:46:25 +000047section~\ref{print}) on a line by itself. (Expression statements
48yielding \code{None} are not written, so that procedure calls do not
49cause any output.)
Fred Drake7a700b82004-01-01 05:43:53 +000050\obindex{None}
Fred Drakef6669171998-05-06 19:52:49 +000051\indexii{string}{conversion}
52\index{output}
53\indexii{standard}{output}
54\indexii{writing}{values}
55\indexii{procedure}{call}
56
Fred Drake2829f1c2001-06-23 05:27:20 +000057
Fred Drake011f6fc1999-04-14 12:52:14 +000058\section{Assert statements \label{assert}}
Guido van Rossum56c20131998-07-24 18:25:38 +000059
Fred Drake011f6fc1999-04-14 12:52:14 +000060Assert statements\stindex{assert} are a convenient way to insert
61debugging assertions\indexii{debugging}{assertions} into a program:
Guido van Rossum56c20131998-07-24 18:25:38 +000062
Fred Drakecb4638a2001-07-06 22:49:53 +000063\begin{productionlist}
Fred Drake007fadd2003-03-31 14:53:03 +000064 \production{assert_stmt}
Fred Drakecb4638a2001-07-06 22:49:53 +000065 {"assert" \token{expression} ["," \token{expression}]}
66\end{productionlist}
Guido van Rossum56c20131998-07-24 18:25:38 +000067
Fred Drake011f6fc1999-04-14 12:52:14 +000068The simple form, \samp{assert expression}, is equivalent to
Guido van Rossum56c20131998-07-24 18:25:38 +000069
70\begin{verbatim}
71if __debug__:
72 if not expression: raise AssertionError
73\end{verbatim}
74
Fred Drake011f6fc1999-04-14 12:52:14 +000075The extended form, \samp{assert expression1, expression2}, is
Guido van Rossum56c20131998-07-24 18:25:38 +000076equivalent to
77
78\begin{verbatim}
79if __debug__:
80 if not expression1: raise AssertionError, expression2
81\end{verbatim}
82
83These equivalences assume that \code{__debug__}\ttindex{__debug__} and
Fred Drake011f6fc1999-04-14 12:52:14 +000084\exception{AssertionError}\exindex{AssertionError} refer to the built-in
Guido van Rossum56c20131998-07-24 18:25:38 +000085variables with those names. In the current implementation, the
Johannes Gijsbersf4a70f32004-12-12 16:52:40 +000086built-in variable \code{__debug__} is \code{True} under normal
87circumstances, \code{False} when optimization is requested (command line
88option -O). The current code generator emits no code for an assert
89statement when optimization is requested at compile time. Note that it
90is unnecessary to include the source code for the expression that failed
91in the error message;
Guido van Rossum56c20131998-07-24 18:25:38 +000092it will be displayed as part of the stack trace.
93
Jeremy Hylton2c84fc82001-03-23 14:34:06 +000094Assignments to \code{__debug__} are illegal. The value for the
95built-in variable is determined when the interpreter starts.
Guido van Rossum56c20131998-07-24 18:25:38 +000096
Fred Drake2829f1c2001-06-23 05:27:20 +000097
Fred Drake011f6fc1999-04-14 12:52:14 +000098\section{Assignment statements \label{assignment}}
Fred Drakef6669171998-05-06 19:52:49 +000099
Fred Drake011f6fc1999-04-14 12:52:14 +0000100Assignment statements\indexii{assignment}{statement} are used to
101(re)bind names to values and to modify attributes or items of mutable
102objects:
Fred Drakef6669171998-05-06 19:52:49 +0000103\indexii{binding}{name}
104\indexii{rebinding}{name}
105\obindex{mutable}
106\indexii{attribute}{assignment}
107
Fred Drakecb4638a2001-07-06 22:49:53 +0000108\begin{productionlist}
109 \production{assignment_stmt}
110 {(\token{target_list} "=")+ \token{expression_list}}
111 \production{target_list}
112 {\token{target} ("," \token{target})* [","]}
113 \production{target}
Fred Drake53815882002-03-15 23:21:37 +0000114 {\token{identifier}}
115 \productioncont{| "(" \token{target_list} ")"}
116 \productioncont{| "[" \token{target_list} "]"}
117 \productioncont{| \token{attributeref}}
118 \productioncont{| \token{subscription}}
119 \productioncont{| \token{slicing}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000120\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000121
Fred Drakec2f496a2001-12-05 05:46:25 +0000122(See section~\ref{primaries} for the syntax definitions for the last
Fred Drakef6669171998-05-06 19:52:49 +0000123three symbols.)
124
125An assignment statement evaluates the expression list (remember that
126this can be a single expression or a comma-separated list, the latter
127yielding a tuple) and assigns the single resulting object to each of
128the target lists, from left to right.
129\indexii{expression}{list}
130
131Assignment is defined recursively depending on the form of the target
132(list). When a target is part of a mutable object (an attribute
133reference, subscription or slicing), the mutable object must
134ultimately perform the assignment and decide about its validity, and
135may raise an exception if the assignment is unacceptable. The rules
136observed by various types and the exceptions raised are given with the
Fred Drakec2f496a2001-12-05 05:46:25 +0000137definition of the object types (see section~\ref{types}).
Fred Drakef6669171998-05-06 19:52:49 +0000138\index{target}
139\indexii{target}{list}
140
141Assignment of an object to a target list is recursively defined as
142follows.
143\indexiii{target}{list}{assignment}
144
145\begin{itemize}
146\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000147If the target list is a single target: The object is assigned to that
Fred Drakef6669171998-05-06 19:52:49 +0000148target.
149
150\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000151If the target list is a comma-separated list of targets: The object
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000152must be a sequence with the same number of items as there are
Guido van Rossum56c20131998-07-24 18:25:38 +0000153targets in the target list, and the items are assigned, from left to
154right, to the corresponding targets. (This rule is relaxed as of
155Python 1.5; in earlier versions, the object had to be a tuple. Since
Fred Drake011f6fc1999-04-14 12:52:14 +0000156strings are sequences, an assignment like \samp{a, b = "xy"} is
Guido van Rossum56c20131998-07-24 18:25:38 +0000157now legal as long as the string has the right length.)
Fred Drakef6669171998-05-06 19:52:49 +0000158
159\end{itemize}
160
161Assignment of an object to a single target is recursively defined as
162follows.
163
164\begin{itemize} % nested
165
166\item
167If the target is an identifier (name):
168
169\begin{itemize}
170
171\item
172If the name does not occur in a \keyword{global} statement in the current
Guido van Rossum56c20131998-07-24 18:25:38 +0000173code block: the name is bound to the object in the current local
174namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000175\stindex{global}
176
177\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000178Otherwise: the name is bound to the object in the current global
179namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000180
181\end{itemize} % nested
182
Guido van Rossum56c20131998-07-24 18:25:38 +0000183The name is rebound if it was already bound. This may cause the
184reference count for the object previously bound to the name to reach
185zero, causing the object to be deallocated and its
186destructor\index{destructor} (if it has one) to be called.
Fred Drakef6669171998-05-06 19:52:49 +0000187
188\item
Guido van Rossum56c20131998-07-24 18:25:38 +0000189If the target is a target list enclosed in parentheses or in square
190brackets: The object must be a sequence with the same number of items
191as there are targets in the target list, and its items are assigned,
192from left to right, to the corresponding targets.
Fred Drakef6669171998-05-06 19:52:49 +0000193
194\item
195If the target is an attribute reference: The primary expression in the
196reference is evaluated. It should yield an object with assignable
197attributes; if this is not the case, \exception{TypeError} is raised. That
198object is then asked to assign the assigned object to the given
199attribute; if it cannot perform the assignment, it raises an exception
200(usually but not necessarily \exception{AttributeError}).
201\indexii{attribute}{assignment}
202
203\item
204If the target is a subscription: The primary expression in the
205reference is evaluated. It should yield either a mutable sequence
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000206object (such as a list) or a mapping object (such as a dictionary). Next,
Guido van Rossum56c20131998-07-24 18:25:38 +0000207the subscript expression is evaluated.
Fred Drakef6669171998-05-06 19:52:49 +0000208\indexii{subscription}{assignment}
209\obindex{mutable}
210
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000211If the primary is a mutable sequence object (such as a list), the subscript
Fred Drakef6669171998-05-06 19:52:49 +0000212must yield a plain integer. If it is negative, the sequence's length
213is added to it. The resulting value must be a nonnegative integer
214less than the sequence's length, and the sequence is asked to assign
215the assigned object to its item with that index. If the index is out
216of range, \exception{IndexError} is raised (assignment to a subscripted
217sequence cannot add new items to a list).
218\obindex{sequence}
219\obindex{list}
220
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000221If the primary is a mapping object (such as a dictionary), the subscript must
Fred Drakef6669171998-05-06 19:52:49 +0000222have a type compatible with the mapping's key type, and the mapping is
223then asked to create a key/datum pair which maps the subscript to
224the assigned object. This can either replace an existing key/value
225pair with the same key value, or insert a new key/value pair (if no
226key with the same value existed).
227\obindex{mapping}
228\obindex{dictionary}
229
230\item
231If the target is a slicing: The primary expression in the reference is
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000232evaluated. It should yield a mutable sequence object (such as a list). The
Fred Drakef6669171998-05-06 19:52:49 +0000233assigned object should be a sequence object of the same type. Next,
234the lower and upper bound expressions are evaluated, insofar they are
235present; defaults are zero and the sequence's length. The bounds
236should evaluate to (small) integers. If either bound is negative, the
237sequence's length is added to it. The resulting bounds are clipped to
238lie between zero and the sequence's length, inclusive. Finally, the
239sequence object is asked to replace the slice with the items of the
240assigned sequence. The length of the slice may be different from the
241length of the assigned sequence, thus changing the length of the
242target sequence, if the object allows it.
243\indexii{slicing}{assignment}
244
245\end{itemize}
Greg Ward38c28e32000-04-27 18:32:02 +0000246
Fred Drakef6669171998-05-06 19:52:49 +0000247(In the current implementation, the syntax for targets is taken
248to be the same as for expressions, and invalid syntax is rejected
249during the code generation phase, causing less detailed error
250messages.)
251
252WARNING: Although the definition of assignment implies that overlaps
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000253between the left-hand side and the right-hand side are `safe' (for example
Fred Drake011f6fc1999-04-14 12:52:14 +0000254\samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
Fred Drakef6669171998-05-06 19:52:49 +0000255collection of assigned-to variables are not safe! For instance, the
Fred Drake011f6fc1999-04-14 12:52:14 +0000256following program prints \samp{[0, 2]}:
Fred Drakef6669171998-05-06 19:52:49 +0000257
258\begin{verbatim}
259x = [0, 1]
260i = 0
261i, x[i] = 1, 2
262print x
263\end{verbatim}
264
265
Fred Drake53815882002-03-15 23:21:37 +0000266\subsection{Augmented assignment statements \label{augassign}}
Fred Drake31f55502000-09-12 20:32:18 +0000267
268Augmented assignment is the combination, in a single statement, of a binary
269operation and an assignment statement:
270\indexii{augmented}{assignment}
271\index{statement!assignment, augmented}
272
Fred Drakecb4638a2001-07-06 22:49:53 +0000273\begin{productionlist}
274 \production{augmented_assignment_stmt}
275 {\token{target} \token{augop} \token{expression_list}}
276 \production{augop}
Fred Drake53815882002-03-15 23:21:37 +0000277 {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}
Fred Drake2269d862004-11-11 06:14:05 +0000278 % The empty groups below prevent conversion to guillemets.
279 \productioncont{| ">{}>=" | "<{}<=" | "\&=" | "\textasciicircum=" | "|="}
Fred Drakecb4638a2001-07-06 22:49:53 +0000280\end{productionlist}
Fred Drake31f55502000-09-12 20:32:18 +0000281
Fred Drakec2f496a2001-12-05 05:46:25 +0000282(See section~\ref{primaries} for the syntax definitions for the last
Fred Drake31f55502000-09-12 20:32:18 +0000283three symbols.)
284
Fred Draked68442b2000-09-21 22:01:36 +0000285An augmented assignment evaluates the target (which, unlike normal
286assignment statements, cannot be an unpacking) and the expression
287list, performs the binary operation specific to the type of assignment
288on the two operands, and assigns the result to the original
289target. The target is only evaluated once.
Fred Drake31f55502000-09-12 20:32:18 +0000290
291An augmented assignment expression like \code{x += 1} can be rewritten as
292\code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
293augmented version, \code{x} is only evaluated once. Also, when possible, the
294actual operation is performed \emph{in-place}, meaning that rather than
295creating a new object and assigning that to the target, the old object is
296modified instead.
297
298With the exception of assigning to tuples and multiple targets in a single
299statement, the assignment done by augmented assignment statements is handled
300the same way as normal assignments. Similarly, with the exception of the
Fred Drakec2f496a2001-12-05 05:46:25 +0000301possible \emph{in-place} behavior, the binary operation performed by
Fred Drake31f55502000-09-12 20:32:18 +0000302augmented assignment is the same as the normal binary operations.
303
Raymond Hettinger04e7e0c2002-06-25 13:36:41 +0000304For targets which are attribute references, the initial value is
305retrieved with a \method{getattr()} and the result is assigned with a
306\method{setattr()}. Notice that the two methods do not necessarily
307refer to the same variable. When \method{getattr()} refers to a class
308variable, \method{setattr()} still writes to an instance variable.
309For example:
310
311\begin{verbatim}
312class A:
313 x = 3 # class variable
314a = A()
315a.x += 1 # writes a.x as 4 leaving A.x as 3
316\end{verbatim}
317
Fred Drake31f55502000-09-12 20:32:18 +0000318
Fred Drake011f6fc1999-04-14 12:52:14 +0000319\section{The \keyword{pass} statement \label{pass}}
Fred Drakef6669171998-05-06 19:52:49 +0000320\stindex{pass}
321
Fred Drakecb4638a2001-07-06 22:49:53 +0000322\begin{productionlist}
323 \production{pass_stmt}
324 {"pass"}
325\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000326
327\keyword{pass} is a null operation --- when it is executed, nothing
328happens. It is useful as a placeholder when a statement is
329required syntactically, but no code needs to be executed, for example:
330\indexii{null}{operation}
331
332\begin{verbatim}
333def f(arg): pass # a function that does nothing (yet)
334
335class C: pass # a class with no methods (yet)
336\end{verbatim}
337
Fred Drake2829f1c2001-06-23 05:27:20 +0000338
Fred Drake011f6fc1999-04-14 12:52:14 +0000339\section{The \keyword{del} statement \label{del}}
Fred Drakef6669171998-05-06 19:52:49 +0000340\stindex{del}
341
Fred Drakecb4638a2001-07-06 22:49:53 +0000342\begin{productionlist}
343 \production{del_stmt}
344 {"del" \token{target_list}}
345\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000346
347Deletion is recursively defined very similar to the way assignment is
348defined. Rather that spelling it out in full details, here are some
349hints.
350\indexii{deletion}{target}
351\indexiii{deletion}{target}{list}
352
353Deletion of a target list recursively deletes each target, from left
354to right.
355
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000356Deletion of a name removes the binding of that name
Guido van Rossum56c20131998-07-24 18:25:38 +0000357from the local or global namespace, depending on whether the name
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000358occurs in a \keyword{global} statement in the same code block. If the
359name is unbound, a \exception{NameError} exception will be raised.
Fred Drakef6669171998-05-06 19:52:49 +0000360\stindex{global}
361\indexii{unbinding}{name}
362
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000363It is illegal to delete a name from the local namespace if it occurs
Michael W. Hudson495afea2002-06-17 12:51:57 +0000364as a free variable\indexii{free}{variable} in a nested block.
Jeremy Hyltond09ed682002-04-01 21:15:14 +0000365
Fred Drakef6669171998-05-06 19:52:49 +0000366Deletion of attribute references, subscriptions and slicings
367is passed to the primary object involved; deletion of a slicing
368is in general equivalent to assignment of an empty slice of the
369right type (but even this is determined by the sliced object).
370\indexii{attribute}{deletion}
371
Fred Drake2829f1c2001-06-23 05:27:20 +0000372
Fred Drake011f6fc1999-04-14 12:52:14 +0000373\section{The \keyword{print} statement \label{print}}
Fred Drakef6669171998-05-06 19:52:49 +0000374\stindex{print}
375
Fred Drakecb4638a2001-07-06 22:49:53 +0000376\begin{productionlist}
377 \production{print_stmt}
Fred Drake53815882002-03-15 23:21:37 +0000378 {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000379 \productioncont{| ">>" \token{expression}
Fred Drake53815882002-03-15 23:21:37 +0000380 \optional{("," \token{expression})+ \optional{","}} )}
Fred Drakecb4638a2001-07-06 22:49:53 +0000381\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000382
Fred Draked4c33521998-10-01 20:39:47 +0000383\keyword{print} evaluates each expression in turn and writes the
384resulting object to standard output (see below). If an object is not
Fred Drakebe9d10e2001-06-23 06:16:52 +0000385a string, it is first converted to a string using the rules for string
Fred Drakef6669171998-05-06 19:52:49 +0000386conversions. The (resulting or original) string is then written. A
Fred Drakebe9d10e2001-06-23 06:16:52 +0000387space is written before each object is (converted and) written, unless
Fred Drakef6669171998-05-06 19:52:49 +0000388the output system believes it is positioned at the beginning of a
Guido van Rossum56c20131998-07-24 18:25:38 +0000389line. This is the case (1) when no characters have yet been written
390to standard output, (2) when the last character written to standard
Fred Draked4c33521998-10-01 20:39:47 +0000391output is \character{\e n}, or (3) when the last write operation on
392standard output was not a \keyword{print} statement. (In some cases
393it may be functional to write an empty string to standard output for
Fred Drakec2f496a2001-12-05 05:46:25 +0000394this reason.) \note{Objects which act like file objects but which are
395not the built-in file objects often do not properly emulate this
396aspect of the file object's behavior, so it is best not to rely on
397this.}
Fred Drakef6669171998-05-06 19:52:49 +0000398\index{output}
399\indexii{writing}{values}
400
Fred Draked4c33521998-10-01 20:39:47 +0000401A \character{\e n} character is written at the end, unless the
402\keyword{print} statement ends with a comma. This is the only action
403if the statement contains just the keyword \keyword{print}.
Fred Drakef6669171998-05-06 19:52:49 +0000404\indexii{trailing}{comma}
405\indexii{newline}{suppression}
406
Fred Drakedde91f01998-05-06 20:59:46 +0000407Standard output is defined as the file object named \code{stdout}
Guido van Rossum56c20131998-07-24 18:25:38 +0000408in the built-in module \module{sys}. If no such object exists, or if
409it does not have a \method{write()} method, a \exception{RuntimeError}
410exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000411\indexii{standard}{output}
412\refbimodindex{sys}
Fred Drake2b3730e1998-11-25 17:40:00 +0000413\withsubitem{(in module sys)}{\ttindex{stdout}}
Fred Drakef6669171998-05-06 19:52:49 +0000414\exindex{RuntimeError}
415
Fred Drakecb4638a2001-07-06 22:49:53 +0000416\keyword{print} also has an extended\index{extended print statement}
417form, defined by the second portion of the syntax described above.
418This form is sometimes referred to as ``\keyword{print} chevron.''
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419In this form, the first expression after the \code{>>} must
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000420evaluate to a ``file-like'' object, specifically an object that has a
Barry Warsaw33f785f2000-08-29 04:57:34 +0000421\method{write()} method as described above. With this extended form,
422the subsequent expressions are printed to this file object. If the
423first expression evaluates to \code{None}, then \code{sys.stdout} is
424used as the file for output.
Barry Warsaw8c0a2422000-08-21 15:45:16 +0000425
Fred Drake2829f1c2001-06-23 05:27:20 +0000426
Fred Drake011f6fc1999-04-14 12:52:14 +0000427\section{The \keyword{return} statement \label{return}}
Fred Drakef6669171998-05-06 19:52:49 +0000428\stindex{return}
429
Fred Drakecb4638a2001-07-06 22:49:53 +0000430\begin{productionlist}
431 \production{return_stmt}
432 {"return" [\token{expression_list}]}
433\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000434
435\keyword{return} may only occur syntactically nested in a function
436definition, not within a nested class definition.
437\indexii{function}{definition}
438\indexii{class}{definition}
439
Guido van Rossum56c20131998-07-24 18:25:38 +0000440If an expression list is present, it is evaluated, else \code{None}
Fred Drakef6669171998-05-06 19:52:49 +0000441is substituted.
442
Guido van Rossum56c20131998-07-24 18:25:38 +0000443\keyword{return} leaves the current function call with the expression
Fred Drakef6669171998-05-06 19:52:49 +0000444list (or \code{None}) as return value.
445
446When \keyword{return} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000447with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000448before really leaving the function.
449\kwindex{finally}
450
Fred Drakee31e9ce2001-12-11 21:10:08 +0000451In a generator function, the \keyword{return} statement is not allowed
452to include an \grammartoken{expression_list}. In that context, a bare
453\keyword{return} indicates that the generator is done and will cause
454\exception{StopIteration} to be raised.
455
456
457\section{The \keyword{yield} statement \label{yield}}
458\stindex{yield}
459
460\begin{productionlist}
461 \production{yield_stmt}
462 {"yield" \token{expression_list}}
463\end{productionlist}
464
465\index{generator!function}
466\index{generator!iterator}
467\index{function!generator}
468\exindex{StopIteration}
469
470The \keyword{yield} statement is only used when defining a generator
471function, and is only used in the body of the generator function.
472Using a \keyword{yield} statement in a function definition is
473sufficient to cause that definition to create a generator function
474instead of a normal function.
475
476When a generator function is called, it returns an iterator known as a
477generator iterator, or more commonly, a generator. The body of the
478generator function is executed by calling the generator's
479\method{next()} method repeatedly until it raises an exception.
480
481When a \keyword{yield} statement is executed, the state of the
482generator is frozen and the value of \grammartoken{expression_list} is
483returned to \method{next()}'s caller. By ``frozen'' we mean that all
484local state is retained, including the current bindings of local
485variables, the instruction pointer, and the internal evaluation stack:
486enough information is saved so that the next time \method{next()} is
487invoked, the function can proceed exactly as if the \keyword{yield}
488statement were just another external call.
489
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490As of Python version 2.5, the \keyword{yield} statement is now
491allowed in the \keyword{try} clause of a \keyword{try} ...\
492\keyword{finally} construct. If the generator is not resumed before
493it is finalized (by reaching a zero reference count or by being garbage
494collected), the generator-iterator's \method{close()} method will be
495called, allowing any pending \keyword{finally} clauses to execute.
Fred Drakee31e9ce2001-12-11 21:10:08 +0000496
Fred Drake08d752c2001-12-14 22:55:14 +0000497\begin{notice}
498In Python 2.2, the \keyword{yield} statement is only allowed
Fred Drake8d0645c2001-12-12 06:06:43 +0000499when the \code{generators} feature has been enabled. It will always
Raymond Hettinger68804312005-01-01 00:28:46 +0000500be enabled in Python 2.3. This \code{__future__} import statement can
Fred Drake08d752c2001-12-14 22:55:14 +0000501be used to enable the feature:
Fred Drake8d0645c2001-12-12 06:06:43 +0000502
503\begin{verbatim}
504from __future__ import generators
505\end{verbatim}
Fred Drake08d752c2001-12-14 22:55:14 +0000506\end{notice}
Fred Drake8d0645c2001-12-12 06:06:43 +0000507
508
Fred Drakee31e9ce2001-12-11 21:10:08 +0000509\begin{seealso}
510 \seepep{0255}{Simple Generators}
511 {The proposal for adding generators and the \keyword{yield}
512 statement to Python.}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000513
514 \seepep{0342}{Coroutines via Enhanced Generators}
515 {The proposal that, among other generator enhancements,
516 proposed allowing \keyword{yield} to appear inside a
517 \keyword{try} ... \keyword{finally} block.}
Fred Drakee31e9ce2001-12-11 21:10:08 +0000518\end{seealso}
519
Fred Drake2829f1c2001-06-23 05:27:20 +0000520
Fred Drake011f6fc1999-04-14 12:52:14 +0000521\section{The \keyword{raise} statement \label{raise}}
Fred Drakef6669171998-05-06 19:52:49 +0000522\stindex{raise}
523
Fred Drakecb4638a2001-07-06 22:49:53 +0000524\begin{productionlist}
525 \production{raise_stmt}
526 {"raise" [\token{expression} ["," \token{expression}
527 ["," \token{expression}]]]}
528\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000529
Guido van Rossum56c20131998-07-24 18:25:38 +0000530If no expressions are present, \keyword{raise} re-raises the last
Raymond Hettingerb56b4942005-04-28 07:18:47 +0000531exception that was active in the current scope. If no exception is
Raymond Hettingerbee0d462005-10-03 16:39:51 +0000532active in the current scope, a \exception{TypeError} exception is
533raised indicating that this is an error (if running under IDLE, a
Neal Norwitzc0d11252005-10-04 03:43:43 +0000534\exception{Queue.Empty} exception is raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000535\index{exception}
536\indexii{raising}{exception}
537
Fred Drake81932e22002-06-20 20:55:29 +0000538Otherwise, \keyword{raise} evaluates the expressions to get three
539objects, using \code{None} as the value of omitted expressions. The
540first two objects are used to determine the \emph{type} and
541\emph{value} of the exception.
Fred Drakef6669171998-05-06 19:52:49 +0000542
Fred Drake81932e22002-06-20 20:55:29 +0000543If the first object is an instance, the type of the exception is the
Fred Drake8bd62af2003-01-25 03:47:35 +0000544class of the instance, the instance itself is the value, and the
Fred Drake81932e22002-06-20 20:55:29 +0000545second object must be \code{None}.
546
547If the first object is a class, it becomes the type of the exception.
548The second object is used to determine the exception value: If it is
549an instance of the class, the instance becomes the exception value.
550If the second object is a tuple, it is used as the argument list for
551the class constructor; if it is \code{None}, an empty argument list is
552used, and any other object is treated as a single argument to the
553constructor. The instance so created by calling the constructor is
554used as the exception value.
555
Fred Drake81932e22002-06-20 20:55:29 +0000556If a third object is present and not \code{None}, it must be a
557traceback\obindex{traceback} object (see section~\ref{traceback}), and
558it is substituted instead of the current location as the place where
559the exception occurred. If the third object is present and not a
560traceback object or \code{None}, a \exception{TypeError} exception is
561raised. The three-expression form of \keyword{raise} is useful to
562re-raise an exception transparently in an except clause, but
563\keyword{raise} with no expressions should be preferred if the
564exception to be re-raised was the most recently active exception in
565the current scope.
566
Fred Drakee7097e02002-10-18 15:18:18 +0000567Additional information on exceptions can be found in
568section~\ref{exceptions}, and information about handling exceptions is
569in section~\ref{try}.
Fred Drakef6669171998-05-06 19:52:49 +0000570
Fred Drake2829f1c2001-06-23 05:27:20 +0000571
Fred Drake011f6fc1999-04-14 12:52:14 +0000572\section{The \keyword{break} statement \label{break}}
Fred Drakef6669171998-05-06 19:52:49 +0000573\stindex{break}
574
Fred Drakecb4638a2001-07-06 22:49:53 +0000575\begin{productionlist}
576 \production{break_stmt}
577 {"break"}
578\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000579
580\keyword{break} may only occur syntactically nested in a \keyword{for}
581or \keyword{while} loop, but not nested in a function or class definition
582within that loop.
583\stindex{for}
584\stindex{while}
585\indexii{loop}{statement}
586
587It terminates the nearest enclosing loop, skipping the optional
Guido van Rossum56c20131998-07-24 18:25:38 +0000588\keyword{else} clause if the loop has one.
Fred Drakef6669171998-05-06 19:52:49 +0000589\kwindex{else}
590
591If a \keyword{for} loop is terminated by \keyword{break}, the loop control
592target keeps its current value.
593\indexii{loop control}{target}
594
595When \keyword{break} passes control out of a \keyword{try} statement
Guido van Rossum56c20131998-07-24 18:25:38 +0000596with a \keyword{finally} clause, that \keyword{finally} clause is executed
Fred Drakef6669171998-05-06 19:52:49 +0000597before really leaving the loop.
598\kwindex{finally}
599
Fred Drake2829f1c2001-06-23 05:27:20 +0000600
Fred Drake011f6fc1999-04-14 12:52:14 +0000601\section{The \keyword{continue} statement \label{continue}}
Fred Drakef6669171998-05-06 19:52:49 +0000602\stindex{continue}
603
Fred Drakecb4638a2001-07-06 22:49:53 +0000604\begin{productionlist}
605 \production{continue_stmt}
606 {"continue"}
607\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000608
609\keyword{continue} may only occur syntactically nested in a \keyword{for} or
610\keyword{while} loop, but not nested in a function or class definition or
Neal Norwitz19f6b862005-10-04 03:37:29 +0000611\keyword{finally} statement within that loop.\footnote{It may
Guido van Rossum56c20131998-07-24 18:25:38 +0000612occur within an \keyword{except} or \keyword{else} clause. The
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000613restriction on occurring in the \keyword{try} clause is implementor's
Guido van Rossum56c20131998-07-24 18:25:38 +0000614laziness and will eventually be lifted.}
615It continues with the next cycle of the nearest enclosing loop.
Fred Drakef6669171998-05-06 19:52:49 +0000616\stindex{for}
617\stindex{while}
618\indexii{loop}{statement}
619\kwindex{finally}
620
Fred Drake2829f1c2001-06-23 05:27:20 +0000621
Fred Drake011f6fc1999-04-14 12:52:14 +0000622\section{The \keyword{import} statement \label{import}}
Fred Drakef6669171998-05-06 19:52:49 +0000623\stindex{import}
Fred Drakeb3be52e2003-07-15 21:37:58 +0000624\index{module!importing}
625\indexii{name}{binding}
626\kwindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000627
Fred Drakecb4638a2001-07-06 22:49:53 +0000628\begin{productionlist}
629 \production{import_stmt}
630 {"import" \token{module} ["as" \token{name}]
Fred Drake53815882002-03-15 23:21:37 +0000631 ( "," \token{module} ["as" \token{name}] )*}
632 \productioncont{| "from" \token{module} "import" \token{identifier}
633 ["as" \token{name}]}
634 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )*}
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000635 \productioncont{| "from" \token{module} "import" "(" \token{identifier}
636 ["as" \token{name}]}
637 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )* [","] ")"}
Fred Drake53815882002-03-15 23:21:37 +0000638 \productioncont{| "from" \token{module} "import" "*"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000639 \production{module}
640 {(\token{identifier} ".")* \token{identifier}}
641\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000642
643Import statements are executed in two steps: (1) find a module, and
644initialize it if necessary; (2) define a name or names in the local
Guido van Rossum56c20131998-07-24 18:25:38 +0000645namespace (of the scope where the \keyword{import} statement occurs).
Fred Drakef6669171998-05-06 19:52:49 +0000646The first form (without \keyword{from}) repeats these steps for each
Guido van Rossum56c20131998-07-24 18:25:38 +0000647identifier in the list. The form with \keyword{from} performs step
648(1) once, and then performs step (2) repeatedly.
Fred Drakef6669171998-05-06 19:52:49 +0000649
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000650In this context, to ``initialize'' a built-in or extension module means to
651call an initialization function that the module must provide for the purpose
652(in the reference implementation, the function's name is obtained by
653prepending string ``init'' to the module's name); to ``initialize'' a
654Python-coded module means to execute the module's body.
655
656The system maintains a table of modules that have been or are being
657initialized,
Fred Drake191a2822000-07-06 00:50:42 +0000658indexed by module name. This table is
Guido van Rossum56c20131998-07-24 18:25:38 +0000659accessible as \code{sys.modules}. When a module name is found in
Fred Drakef6669171998-05-06 19:52:49 +0000660this table, step (1) is finished. If not, a search for a module
Guido van Rossum56c20131998-07-24 18:25:38 +0000661definition is started. When a module is found, it is loaded. Details
662of the module searching and loading process are implementation and
663platform specific. It generally involves searching for a ``built-in''
664module with the given name and then searching a list of locations
665given as \code{sys.path}.
Fred Drake2b3730e1998-11-25 17:40:00 +0000666\withsubitem{(in module sys)}{\ttindex{modules}}
Fred Drakef6669171998-05-06 19:52:49 +0000667\ttindex{sys.modules}
668\indexii{module}{name}
669\indexii{built-in}{module}
670\indexii{user-defined}{module}
671\refbimodindex{sys}
Fred Drakef6669171998-05-06 19:52:49 +0000672\indexii{filename}{extension}
Fred Drakedde91f01998-05-06 20:59:46 +0000673\indexiii{module}{search}{path}
Fred Drakef6669171998-05-06 19:52:49 +0000674
Fred Draked51ce7d2003-07-15 22:03:00 +0000675If a built-in module is found,\indexii{module}{initialization} its
676built-in initialization code is executed and step (1) is finished. If
677no matching file is found,
678\exception{ImportError}\exindex{ImportError} is raised.
679\index{code block}If a file is found, it is parsed,
Fred Drakef6669171998-05-06 19:52:49 +0000680yielding an executable code block. If a syntax error occurs,
Fred Draked51ce7d2003-07-15 22:03:00 +0000681\exception{SyntaxError}\exindex{SyntaxError} is raised. Otherwise, an
682empty module of the given name is created and inserted in the module
683table, and then the code block is executed in the context of this
684module. Exceptions during this execution terminate step (1).
Fred Drakef6669171998-05-06 19:52:49 +0000685
686When step (1) finishes without raising an exception, step (2) can
687begin.
688
Fred Drake859eb622001-03-06 07:34:00 +0000689The first form of \keyword{import} statement binds the module name in
690the local namespace to the module object, and then goes on to import
691the next identifier, if any. If the module name is followed by
692\keyword{as}, the name following \keyword{as} is used as the local
Martin v. Löwis13dd9d92003-01-16 11:30:08 +0000693name for the module.
Thomas Wouters8bad6122000-08-19 20:55:02 +0000694
Thomas Wouters52152252000-08-17 22:55:00 +0000695The \keyword{from} form does not bind the module name: it goes through the
696list of identifiers, looks each one of them up in the module found in step
697(1), and binds the name in the local namespace to the object thus found.
Fred Draked68442b2000-09-21 22:01:36 +0000698As with the first form of \keyword{import}, an alternate local name can be
Thomas Wouters52152252000-08-17 22:55:00 +0000699supplied by specifying "\keyword{as} localname". If a name is not found,
Fred Drakef6669171998-05-06 19:52:49 +0000700\exception{ImportError} is raised. If the list of identifiers is replaced
Fred Drake08fd5152001-10-24 19:50:31 +0000701by a star (\character{*}), all public names defined in the module are
702bound in the local namespace of the \keyword{import} statement..
Fred Drakef6669171998-05-06 19:52:49 +0000703\indexii{name}{binding}
704\exindex{ImportError}
705
Fred Drake08fd5152001-10-24 19:50:31 +0000706The \emph{public names} defined by a module are determined by checking
707the module's namespace for a variable named \code{__all__}; if
708defined, it must be a sequence of strings which are names defined or
709imported by that module. The names given in \code{__all__} are all
710considered public and are required to exist. If \code{__all__} is not
711defined, the set of public names includes all names found in the
712module's namespace which do not begin with an underscore character
Raymond Hettinger1772f172003-01-06 12:54:54 +0000713(\character{_}). \code{__all__} should contain the entire public API.
714It is intended to avoid accidentally exporting items that are not part
715of the API (such as library modules which were imported and used within
716the module).
Fred Drake27cae1f2002-12-07 16:00:00 +0000717\withsubitem{(optional module attribute)}{\ttindex{__all__}}
Fred Drake08fd5152001-10-24 19:50:31 +0000718
Jeremy Hyltonf0c1f1b2002-04-01 21:19:44 +0000719The \keyword{from} form with \samp{*} may only occur in a module
720scope. If the wild card form of import --- \samp{import *} --- is
721used in a function and the function contains or is a nested block with
722free variables, the compiler will raise a \exception{SyntaxError}.
723
Fred Drakef6669171998-05-06 19:52:49 +0000724\kwindex{from}
Fred Drake2b3730e1998-11-25 17:40:00 +0000725\stindex{from}
Fred Drakef6669171998-05-06 19:52:49 +0000726
Fred Drake246837d1998-07-24 20:28:22 +0000727\strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
Guido van Rossum56c20131998-07-24 18:25:38 +0000728when the module names contains one or more dots, the module search
729path is carried out differently. The sequence of identifiers up to
730the last dot is used to find a ``package''\index{packages}; the final
731identifier is then searched inside the package. A package is
732generally a subdirectory of a directory on \code{sys.path} that has a
733file \file{__init__.py}.\ttindex{__init__.py}
734%
735[XXX Can't be bothered to spell this out right now; see the URL
Fred Drake1a0b8721998-08-07 17:40:20 +0000736\url{http://www.python.org/doc/essays/packages.html} for more details, also
Guido van Rossum56c20131998-07-24 18:25:38 +0000737about how the module search works from inside a package.]
738
Fred Drake08fd5152001-10-24 19:50:31 +0000739The built-in function \function{__import__()} is provided to support
740applications that determine which modules need to be loaded
741dynamically; refer to \ulink{Built-in
742Functions}{../lib/built-in-funcs.html} in the
743\citetitle[../lib/lib.html]{Python Library Reference} for additional
744information.
Guido van Rossum56c20131998-07-24 18:25:38 +0000745\bifuncindex{__import__}
746
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000747\subsection{Future statements \label{future}}
748
749A \dfn{future statement}\indexii{future}{statement} is a directive to
750the compiler that a particular module should be compiled using syntax
751or semantics that will be available in a specified future release of
752Python. The future statement is intended to ease migration to future
753versions of Python that introduce incompatible changes to the
754language. It allows use of the new features on a per-module basis
755before the release in which the feature becomes standard.
756
757\begin{productionlist}[*]
758 \production{future_statement}
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000759 {"from" "__future__" "import" feature ["as" name] ("," feature ["as" name])*}
760 \productioncont{| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])* [","] ")"}
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000761 \production{feature}{identifier}
762 \production{name}{identifier}
763\end{productionlist}
764
765A future statement must appear near the top of the module. The only
766lines that can appear before a future statement are:
767
768\begin{itemize}
769
770\item the module docstring (if any),
771\item comments,
772\item blank lines, and
773\item other future statements.
774
775\end{itemize}
776
777The features recognized by Python 2.3 are \samp{generators},
778\samp{division} and \samp{nested_scopes}. \samp{generators} and
779\samp{nested_scopes} are redundant in 2.3 because they are always
780enabled.
781
782A future statement is recognized and treated specially at compile
783time: Changes to the semantics of core constructs are often
784implemented by generating different code. It may even be the case
785that a new feature introduces new incompatible syntax (such as a new
786reserved word), in which case the compiler may need to parse the
787module differently. Such decisions cannot be pushed off until
788runtime.
789
790For any given release, the compiler knows which feature names have been
791defined, and raises a compile-time error if a future statement contains
792a feature not known to it.
793
794The direct runtime semantics are the same as for any import statement:
795there is a standard module \module{__future__}, described later, and
796it will be imported in the usual way at the time the future statement
797is executed.
798
799The interesting runtime semantics depend on the specific feature
800enabled by the future statement.
801
802Note that there is nothing special about the statement:
803
804\begin{verbatim}
805import __future__ [as name]
806\end{verbatim}
807
808That is not a future statement; it's an ordinary import statement with
809no special semantics or syntax restrictions.
810
Georg Brandl7cae87c2006-09-06 06:51:57 +0000811Code compiled by calls to the builtin functions \function{exec()},
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000812\function{compile()} and \function{execfile()} that occur in a module
813\module{M} containing a future statement will, by default, use the new
814syntax or semantics associated with the future statement. This can,
815starting with Python 2.2 be controlled by optional arguments to
Thomas Wouters477c8d52006-05-27 19:21:47 +0000816\function{compile()} --- see the documentation of that function in the
817\citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
818details.
Jeremy Hylton8bea5dc2003-05-21 21:43:00 +0000819
820A future statement typed at an interactive interpreter prompt will
821take effect for the rest of the interpreter session. If an
822interpreter is started with the \programopt{-i} option, is passed a
823script name to execute, and the script includes a future statement, it
824will be in effect in the interactive session started after the script
825is executed.
Fred Drake2829f1c2001-06-23 05:27:20 +0000826
Fred Drake011f6fc1999-04-14 12:52:14 +0000827\section{The \keyword{global} statement \label{global}}
Fred Drakef6669171998-05-06 19:52:49 +0000828\stindex{global}
829
Fred Drakecb4638a2001-07-06 22:49:53 +0000830\begin{productionlist}
831 \production{global_stmt}
832 {"global" \token{identifier} ("," \token{identifier})*}
833\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000834
835The \keyword{global} statement is a declaration which holds for the
836entire current code block. It means that the listed identifiers are to be
Jeremy Hyltonf3255c82002-04-01 21:25:32 +0000837interpreted as globals. It would be impossible to assign to a global
838variable without \keyword{global}, although free variables may refer
839to globals without being declared global.
Fred Drakef6669171998-05-06 19:52:49 +0000840\indexiii{global}{name}{binding}
841
842Names listed in a \keyword{global} statement must not be used in the same
Guido van Rossumb1f97d61998-12-21 18:57:36 +0000843code block textually preceding that \keyword{global} statement.
Fred Drakef6669171998-05-06 19:52:49 +0000844
845Names listed in a \keyword{global} statement must not be defined as formal
846parameters or in a \keyword{for} loop control target, \keyword{class}
847definition, function definition, or \keyword{import} statement.
848
849(The current implementation does not enforce the latter two
850restrictions, but programs should not abuse this freedom, as future
851implementations may enforce them or silently change the meaning of the
852program.)
853
Guido van Rossum56c20131998-07-24 18:25:38 +0000854\strong{Programmer's note:}
855the \keyword{global} is a directive to the parser. It
Fred Drakef6669171998-05-06 19:52:49 +0000856applies only to code parsed at the same time as the \keyword{global}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000857statement. In particular, a \keyword{global} statement contained in a
858string or code object supplied to the builtin \function{exec()} function
859does not affect the code block \emph{containing} the function call,
860and code contained in such a string is unaffected by \keyword{global}
861statements in the code containing the function call. The same applies to the
Fred Drakef6669171998-05-06 19:52:49 +0000862\function{eval()}, \function{execfile()} and \function{compile()} functions.
Georg Brandl7cae87c2006-09-06 06:51:57 +0000863\bifuncindex{exec}
Fred Drakef6669171998-05-06 19:52:49 +0000864\bifuncindex{eval}
865\bifuncindex{execfile}
866\bifuncindex{compile}
Guido van Rossum5f574aa1998-07-06 13:18:39 +0000867