1 | \chapter{Simple statements \label{simple}}
|
---|
2 | \indexii{simple}{statement}
|
---|
3 |
|
---|
4 | Simple statements are comprised within a single logical line.
|
---|
5 | Several simple statements may occur on a single line separated
|
---|
6 | by semicolons. The syntax for simple statements is:
|
---|
7 |
|
---|
8 | \begin{productionlist}
|
---|
9 | \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}}
|
---|
24 | \end{productionlist}
|
---|
25 |
|
---|
26 |
|
---|
27 | \section{Expression statements \label{exprstmts}}
|
---|
28 | \indexii{expression}{statement}
|
---|
29 |
|
---|
30 | Expression statements are used (mostly interactively) to compute and
|
---|
31 | write a value, or (usually) to call a procedure (a function that
|
---|
32 | returns no meaningful result; in Python, procedures return the value
|
---|
33 | \code{None}). Other uses of expression statements are allowed and
|
---|
34 | occasionally useful. The syntax for an expression statement is:
|
---|
35 |
|
---|
36 | \begin{productionlist}
|
---|
37 | \production{expression_stmt}
|
---|
38 | {\token{expression_list}}
|
---|
39 | \end{productionlist}
|
---|
40 |
|
---|
41 | An expression statement evaluates the expression list (which may be a
|
---|
42 | single expression).
|
---|
43 | \indexii{expression}{list}
|
---|
44 |
|
---|
45 | In interactive mode, if the value is not \code{None}, it is converted
|
---|
46 | to a string using the built-in \function{repr()}\bifuncindex{repr}
|
---|
47 | function and the resulting string is written to standard output (see
|
---|
48 | section~\ref{print}) on a line by itself. (Expression statements
|
---|
49 | yielding \code{None} are not written, so that procedure calls do not
|
---|
50 | cause any output.)
|
---|
51 | \obindex{None}
|
---|
52 | \indexii{string}{conversion}
|
---|
53 | \index{output}
|
---|
54 | \indexii{standard}{output}
|
---|
55 | \indexii{writing}{values}
|
---|
56 | \indexii{procedure}{call}
|
---|
57 |
|
---|
58 |
|
---|
59 | \section{Assert statements \label{assert}}
|
---|
60 |
|
---|
61 | Assert statements\stindex{assert} are a convenient way to insert
|
---|
62 | debugging assertions\indexii{debugging}{assertions} into a program:
|
---|
63 |
|
---|
64 | \begin{productionlist}
|
---|
65 | \production{assert_stmt}
|
---|
66 | {"assert" \token{expression} ["," \token{expression}]}
|
---|
67 | \end{productionlist}
|
---|
68 |
|
---|
69 | The simple form, \samp{assert expression}, is equivalent to
|
---|
70 |
|
---|
71 | \begin{verbatim}
|
---|
72 | if __debug__:
|
---|
73 | if not expression: raise AssertionError
|
---|
74 | \end{verbatim}
|
---|
75 |
|
---|
76 | The extended form, \samp{assert expression1, expression2}, is
|
---|
77 | equivalent to
|
---|
78 |
|
---|
79 | \begin{verbatim}
|
---|
80 | if __debug__:
|
---|
81 | if not expression1: raise AssertionError, expression2
|
---|
82 | \end{verbatim}
|
---|
83 |
|
---|
84 | These equivalences assume that \code{__debug__}\ttindex{__debug__} and
|
---|
85 | \exception{AssertionError}\exindex{AssertionError} refer to the built-in
|
---|
86 | variables with those names. In the current implementation, the
|
---|
87 | built-in variable \code{__debug__} is \code{True} under normal
|
---|
88 | circumstances, \code{False} when optimization is requested (command line
|
---|
89 | option -O). The current code generator emits no code for an assert
|
---|
90 | statement when optimization is requested at compile time. Note that it
|
---|
91 | is unnecessary to include the source code for the expression that failed
|
---|
92 | in the error message;
|
---|
93 | it will be displayed as part of the stack trace.
|
---|
94 |
|
---|
95 | Assignments to \code{__debug__} are illegal. The value for the
|
---|
96 | built-in variable is determined when the interpreter starts.
|
---|
97 |
|
---|
98 |
|
---|
99 | \section{Assignment statements \label{assignment}}
|
---|
100 |
|
---|
101 | Assignment statements\indexii{assignment}{statement} are used to
|
---|
102 | (re)bind names to values and to modify attributes or items of mutable
|
---|
103 | objects:
|
---|
104 | \indexii{binding}{name}
|
---|
105 | \indexii{rebinding}{name}
|
---|
106 | \obindex{mutable}
|
---|
107 | \indexii{attribute}{assignment}
|
---|
108 |
|
---|
109 | \begin{productionlist}
|
---|
110 | \production{assignment_stmt}
|
---|
111 | {(\token{target_list} "=")+ \token{expression_list}}
|
---|
112 | \production{target_list}
|
---|
113 | {\token{target} ("," \token{target})* [","]}
|
---|
114 | \production{target}
|
---|
115 | {\token{identifier}}
|
---|
116 | \productioncont{| "(" \token{target_list} ")"}
|
---|
117 | \productioncont{| "[" \token{target_list} "]"}
|
---|
118 | \productioncont{| \token{attributeref}}
|
---|
119 | \productioncont{| \token{subscription}}
|
---|
120 | \productioncont{| \token{slicing}}
|
---|
121 | \end{productionlist}
|
---|
122 |
|
---|
123 | (See section~\ref{primaries} for the syntax definitions for the last
|
---|
124 | three symbols.)
|
---|
125 |
|
---|
126 | An assignment statement evaluates the expression list (remember that
|
---|
127 | this can be a single expression or a comma-separated list, the latter
|
---|
128 | yielding a tuple) and assigns the single resulting object to each of
|
---|
129 | the target lists, from left to right.
|
---|
130 | \indexii{expression}{list}
|
---|
131 |
|
---|
132 | Assignment is defined recursively depending on the form of the target
|
---|
133 | (list). When a target is part of a mutable object (an attribute
|
---|
134 | reference, subscription or slicing), the mutable object must
|
---|
135 | ultimately perform the assignment and decide about its validity, and
|
---|
136 | may raise an exception if the assignment is unacceptable. The rules
|
---|
137 | observed by various types and the exceptions raised are given with the
|
---|
138 | definition of the object types (see section~\ref{types}).
|
---|
139 | \index{target}
|
---|
140 | \indexii{target}{list}
|
---|
141 |
|
---|
142 | Assignment of an object to a target list is recursively defined as
|
---|
143 | follows.
|
---|
144 | \indexiii{target}{list}{assignment}
|
---|
145 |
|
---|
146 | \begin{itemize}
|
---|
147 | \item
|
---|
148 | If the target list is a single target: The object is assigned to that
|
---|
149 | target.
|
---|
150 |
|
---|
151 | \item
|
---|
152 | If the target list is a comma-separated list of targets: The object
|
---|
153 | must be a sequence with the same number of items as there are
|
---|
154 | targets in the target list, and the items are assigned, from left to
|
---|
155 | right, to the corresponding targets. (This rule is relaxed as of
|
---|
156 | Python 1.5; in earlier versions, the object had to be a tuple. Since
|
---|
157 | strings are sequences, an assignment like \samp{a, b = "xy"} is
|
---|
158 | now legal as long as the string has the right length.)
|
---|
159 |
|
---|
160 | \end{itemize}
|
---|
161 |
|
---|
162 | Assignment of an object to a single target is recursively defined as
|
---|
163 | follows.
|
---|
164 |
|
---|
165 | \begin{itemize} % nested
|
---|
166 |
|
---|
167 | \item
|
---|
168 | If the target is an identifier (name):
|
---|
169 |
|
---|
170 | \begin{itemize}
|
---|
171 |
|
---|
172 | \item
|
---|
173 | If the name does not occur in a \keyword{global} statement in the current
|
---|
174 | code block: the name is bound to the object in the current local
|
---|
175 | namespace.
|
---|
176 | \stindex{global}
|
---|
177 |
|
---|
178 | \item
|
---|
179 | Otherwise: the name is bound to the object in the current global
|
---|
180 | namespace.
|
---|
181 |
|
---|
182 | \end{itemize} % nested
|
---|
183 |
|
---|
184 | The name is rebound if it was already bound. This may cause the
|
---|
185 | reference count for the object previously bound to the name to reach
|
---|
186 | zero, causing the object to be deallocated and its
|
---|
187 | destructor\index{destructor} (if it has one) to be called.
|
---|
188 |
|
---|
189 | \item
|
---|
190 | If the target is a target list enclosed in parentheses or in square
|
---|
191 | brackets: The object must be a sequence with the same number of items
|
---|
192 | as there are targets in the target list, and its items are assigned,
|
---|
193 | from left to right, to the corresponding targets.
|
---|
194 |
|
---|
195 | \item
|
---|
196 | If the target is an attribute reference: The primary expression in the
|
---|
197 | reference is evaluated. It should yield an object with assignable
|
---|
198 | attributes; if this is not the case, \exception{TypeError} is raised. That
|
---|
199 | object is then asked to assign the assigned object to the given
|
---|
200 | attribute; if it cannot perform the assignment, it raises an exception
|
---|
201 | (usually but not necessarily \exception{AttributeError}).
|
---|
202 | \indexii{attribute}{assignment}
|
---|
203 |
|
---|
204 | \item
|
---|
205 | If the target is a subscription: The primary expression in the
|
---|
206 | reference is evaluated. It should yield either a mutable sequence
|
---|
207 | object (such as a list) or a mapping object (such as a dictionary). Next,
|
---|
208 | the subscript expression is evaluated.
|
---|
209 | \indexii{subscription}{assignment}
|
---|
210 | \obindex{mutable}
|
---|
211 |
|
---|
212 | If the primary is a mutable sequence object (such as a list), the subscript
|
---|
213 | must yield a plain integer. If it is negative, the sequence's length
|
---|
214 | is added to it. The resulting value must be a nonnegative integer
|
---|
215 | less than the sequence's length, and the sequence is asked to assign
|
---|
216 | the assigned object to its item with that index. If the index is out
|
---|
217 | of range, \exception{IndexError} is raised (assignment to a subscripted
|
---|
218 | sequence cannot add new items to a list).
|
---|
219 | \obindex{sequence}
|
---|
220 | \obindex{list}
|
---|
221 |
|
---|
222 | If the primary is a mapping object (such as a dictionary), the subscript must
|
---|
223 | have a type compatible with the mapping's key type, and the mapping is
|
---|
224 | then asked to create a key/datum pair which maps the subscript to
|
---|
225 | the assigned object. This can either replace an existing key/value
|
---|
226 | pair with the same key value, or insert a new key/value pair (if no
|
---|
227 | key with the same value existed).
|
---|
228 | \obindex{mapping}
|
---|
229 | \obindex{dictionary}
|
---|
230 |
|
---|
231 | \item
|
---|
232 | If the target is a slicing: The primary expression in the reference is
|
---|
233 | evaluated. It should yield a mutable sequence object (such as a list). The
|
---|
234 | assigned object should be a sequence object of the same type. Next,
|
---|
235 | the lower and upper bound expressions are evaluated, insofar they are
|
---|
236 | present; defaults are zero and the sequence's length. The bounds
|
---|
237 | should evaluate to (small) integers. If either bound is negative, the
|
---|
238 | sequence's length is added to it. The resulting bounds are clipped to
|
---|
239 | lie between zero and the sequence's length, inclusive. Finally, the
|
---|
240 | sequence object is asked to replace the slice with the items of the
|
---|
241 | assigned sequence. The length of the slice may be different from the
|
---|
242 | length of the assigned sequence, thus changing the length of the
|
---|
243 | target sequence, if the object allows it.
|
---|
244 | \indexii{slicing}{assignment}
|
---|
245 |
|
---|
246 | \end{itemize}
|
---|
247 |
|
---|
248 | (In the current implementation, the syntax for targets is taken
|
---|
249 | to be the same as for expressions, and invalid syntax is rejected
|
---|
250 | during the code generation phase, causing less detailed error
|
---|
251 | messages.)
|
---|
252 |
|
---|
253 | WARNING: Although the definition of assignment implies that overlaps
|
---|
254 | between the left-hand side and the right-hand side are `safe' (for example
|
---|
255 | \samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
|
---|
256 | collection of assigned-to variables are not safe! For instance, the
|
---|
257 | following program prints \samp{[0, 2]}:
|
---|
258 |
|
---|
259 | \begin{verbatim}
|
---|
260 | x = [0, 1]
|
---|
261 | i = 0
|
---|
262 | i, x[i] = 1, 2
|
---|
263 | print x
|
---|
264 | \end{verbatim}
|
---|
265 |
|
---|
266 |
|
---|
267 | \subsection{Augmented assignment statements \label{augassign}}
|
---|
268 |
|
---|
269 | Augmented assignment is the combination, in a single statement, of a binary
|
---|
270 | operation and an assignment statement:
|
---|
271 | \indexii{augmented}{assignment}
|
---|
272 | \index{statement!assignment, augmented}
|
---|
273 |
|
---|
274 | \begin{productionlist}
|
---|
275 | \production{augmented_assignment_stmt}
|
---|
276 | {\token{target} \token{augop} \token{expression_list}}
|
---|
277 | \production{augop}
|
---|
278 | {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}
|
---|
279 | % The empty groups below prevent conversion to guillemets.
|
---|
280 | \productioncont{| ">{}>=" | "<{}<=" | "\&=" | "\textasciicircum=" | "|="}
|
---|
281 | \end{productionlist}
|
---|
282 |
|
---|
283 | (See section~\ref{primaries} for the syntax definitions for the last
|
---|
284 | three symbols.)
|
---|
285 |
|
---|
286 | An augmented assignment evaluates the target (which, unlike normal
|
---|
287 | assignment statements, cannot be an unpacking) and the expression
|
---|
288 | list, performs the binary operation specific to the type of assignment
|
---|
289 | on the two operands, and assigns the result to the original
|
---|
290 | target. The target is only evaluated once.
|
---|
291 |
|
---|
292 | An augmented assignment expression like \code{x += 1} can be rewritten as
|
---|
293 | \code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
|
---|
294 | augmented version, \code{x} is only evaluated once. Also, when possible, the
|
---|
295 | actual operation is performed \emph{in-place}, meaning that rather than
|
---|
296 | creating a new object and assigning that to the target, the old object is
|
---|
297 | modified instead.
|
---|
298 |
|
---|
299 | With the exception of assigning to tuples and multiple targets in a single
|
---|
300 | statement, the assignment done by augmented assignment statements is handled
|
---|
301 | the same way as normal assignments. Similarly, with the exception of the
|
---|
302 | possible \emph{in-place} behavior, the binary operation performed by
|
---|
303 | augmented assignment is the same as the normal binary operations.
|
---|
304 |
|
---|
305 | For targets which are attribute references, the initial value is
|
---|
306 | retrieved with a \method{getattr()} and the result is assigned with a
|
---|
307 | \method{setattr()}. Notice that the two methods do not necessarily
|
---|
308 | refer to the same variable. When \method{getattr()} refers to a class
|
---|
309 | variable, \method{setattr()} still writes to an instance variable.
|
---|
310 | For example:
|
---|
311 |
|
---|
312 | \begin{verbatim}
|
---|
313 | class A:
|
---|
314 | x = 3 # class variable
|
---|
315 | a = A()
|
---|
316 | a.x += 1 # writes a.x as 4 leaving A.x as 3
|
---|
317 | \end{verbatim}
|
---|
318 |
|
---|
319 |
|
---|
320 | \section{The \keyword{pass} statement \label{pass}}
|
---|
321 | \stindex{pass}
|
---|
322 |
|
---|
323 | \begin{productionlist}
|
---|
324 | \production{pass_stmt}
|
---|
325 | {"pass"}
|
---|
326 | \end{productionlist}
|
---|
327 |
|
---|
328 | \keyword{pass} is a null operation --- when it is executed, nothing
|
---|
329 | happens. It is useful as a placeholder when a statement is
|
---|
330 | required syntactically, but no code needs to be executed, for example:
|
---|
331 | \indexii{null}{operation}
|
---|
332 |
|
---|
333 | \begin{verbatim}
|
---|
334 | def f(arg): pass # a function that does nothing (yet)
|
---|
335 |
|
---|
336 | class C: pass # a class with no methods (yet)
|
---|
337 | \end{verbatim}
|
---|
338 |
|
---|
339 |
|
---|
340 | \section{The \keyword{del} statement \label{del}}
|
---|
341 | \stindex{del}
|
---|
342 |
|
---|
343 | \begin{productionlist}
|
---|
344 | \production{del_stmt}
|
---|
345 | {"del" \token{target_list}}
|
---|
346 | \end{productionlist}
|
---|
347 |
|
---|
348 | Deletion is recursively defined very similar to the way assignment is
|
---|
349 | defined. Rather that spelling it out in full details, here are some
|
---|
350 | hints.
|
---|
351 | \indexii{deletion}{target}
|
---|
352 | \indexiii{deletion}{target}{list}
|
---|
353 |
|
---|
354 | Deletion of a target list recursively deletes each target, from left
|
---|
355 | to right.
|
---|
356 |
|
---|
357 | Deletion of a name removes the binding of that name
|
---|
358 | from the local or global namespace, depending on whether the name
|
---|
359 | occurs in a \keyword{global} statement in the same code block. If the
|
---|
360 | name is unbound, a \exception{NameError} exception will be raised.
|
---|
361 | \stindex{global}
|
---|
362 | \indexii{unbinding}{name}
|
---|
363 |
|
---|
364 | It is illegal to delete a name from the local namespace if it occurs
|
---|
365 | as a free variable\indexii{free}{variable} in a nested block.
|
---|
366 |
|
---|
367 | Deletion of attribute references, subscriptions and slicings
|
---|
368 | is passed to the primary object involved; deletion of a slicing
|
---|
369 | is in general equivalent to assignment of an empty slice of the
|
---|
370 | right type (but even this is determined by the sliced object).
|
---|
371 | \indexii{attribute}{deletion}
|
---|
372 |
|
---|
373 |
|
---|
374 | \section{The \keyword{print} statement \label{print}}
|
---|
375 | \stindex{print}
|
---|
376 |
|
---|
377 | \begin{productionlist}
|
---|
378 | \production{print_stmt}
|
---|
379 | {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}}
|
---|
380 | \productioncont{| ">>" \token{expression}
|
---|
381 | \optional{("," \token{expression})+ \optional{","}} )}
|
---|
382 | \end{productionlist}
|
---|
383 |
|
---|
384 | \keyword{print} evaluates each expression in turn and writes the
|
---|
385 | resulting object to standard output (see below). If an object is not
|
---|
386 | a string, it is first converted to a string using the rules for string
|
---|
387 | conversions. The (resulting or original) string is then written. A
|
---|
388 | space is written before each object is (converted and) written, unless
|
---|
389 | the output system believes it is positioned at the beginning of a
|
---|
390 | line. This is the case (1) when no characters have yet been written
|
---|
391 | to standard output, (2) when the last character written to standard
|
---|
392 | output is \character{\e n}, or (3) when the last write operation on
|
---|
393 | standard output was not a \keyword{print} statement. (In some cases
|
---|
394 | it may be functional to write an empty string to standard output for
|
---|
395 | this reason.) \note{Objects which act like file objects but which are
|
---|
396 | not the built-in file objects often do not properly emulate this
|
---|
397 | aspect of the file object's behavior, so it is best not to rely on
|
---|
398 | this.}
|
---|
399 | \index{output}
|
---|
400 | \indexii{writing}{values}
|
---|
401 |
|
---|
402 | A \character{\e n} character is written at the end, unless the
|
---|
403 | \keyword{print} statement ends with a comma. This is the only action
|
---|
404 | if the statement contains just the keyword \keyword{print}.
|
---|
405 | \indexii{trailing}{comma}
|
---|
406 | \indexii{newline}{suppression}
|
---|
407 |
|
---|
408 | Standard output is defined as the file object named \code{stdout}
|
---|
409 | in the built-in module \module{sys}. If no such object exists, or if
|
---|
410 | it does not have a \method{write()} method, a \exception{RuntimeError}
|
---|
411 | exception is raised.
|
---|
412 | \indexii{standard}{output}
|
---|
413 | \refbimodindex{sys}
|
---|
414 | \withsubitem{(in module sys)}{\ttindex{stdout}}
|
---|
415 | \exindex{RuntimeError}
|
---|
416 |
|
---|
417 | \keyword{print} also has an extended\index{extended print statement}
|
---|
418 | form, defined by the second portion of the syntax described above.
|
---|
419 | This form is sometimes referred to as ``\keyword{print} chevron.''
|
---|
420 | In this form, the first expression after the \code{>>} must
|
---|
421 | evaluate to a ``file-like'' object, specifically an object that has a
|
---|
422 | \method{write()} method as described above. With this extended form,
|
---|
423 | the subsequent expressions are printed to this file object. If the
|
---|
424 | first expression evaluates to \code{None}, then \code{sys.stdout} is
|
---|
425 | used as the file for output.
|
---|
426 |
|
---|
427 |
|
---|
428 | \section{The \keyword{return} statement \label{return}}
|
---|
429 | \stindex{return}
|
---|
430 |
|
---|
431 | \begin{productionlist}
|
---|
432 | \production{return_stmt}
|
---|
433 | {"return" [\token{expression_list}]}
|
---|
434 | \end{productionlist}
|
---|
435 |
|
---|
436 | \keyword{return} may only occur syntactically nested in a function
|
---|
437 | definition, not within a nested class definition.
|
---|
438 | \indexii{function}{definition}
|
---|
439 | \indexii{class}{definition}
|
---|
440 |
|
---|
441 | If an expression list is present, it is evaluated, else \code{None}
|
---|
442 | is substituted.
|
---|
443 |
|
---|
444 | \keyword{return} leaves the current function call with the expression
|
---|
445 | list (or \code{None}) as return value.
|
---|
446 |
|
---|
447 | When \keyword{return} passes control out of a \keyword{try} statement
|
---|
448 | with a \keyword{finally} clause, that \keyword{finally} clause is executed
|
---|
449 | before really leaving the function.
|
---|
450 | \kwindex{finally}
|
---|
451 |
|
---|
452 | In a generator function, the \keyword{return} statement is not allowed
|
---|
453 | to include an \grammartoken{expression_list}. In that context, a bare
|
---|
454 | \keyword{return} indicates that the generator is done and will cause
|
---|
455 | \exception{StopIteration} to be raised.
|
---|
456 |
|
---|
457 |
|
---|
458 | \section{The \keyword{yield} statement \label{yield}}
|
---|
459 | \stindex{yield}
|
---|
460 |
|
---|
461 | \begin{productionlist}
|
---|
462 | \production{yield_stmt}
|
---|
463 | {"yield" \token{expression_list}}
|
---|
464 | \end{productionlist}
|
---|
465 |
|
---|
466 | \index{generator!function}
|
---|
467 | \index{generator!iterator}
|
---|
468 | \index{function!generator}
|
---|
469 | \exindex{StopIteration}
|
---|
470 |
|
---|
471 | The \keyword{yield} statement is only used when defining a generator
|
---|
472 | function, and is only used in the body of the generator function.
|
---|
473 | Using a \keyword{yield} statement in a function definition is
|
---|
474 | sufficient to cause that definition to create a generator function
|
---|
475 | instead of a normal function.
|
---|
476 |
|
---|
477 | When a generator function is called, it returns an iterator known as a
|
---|
478 | generator iterator, or more commonly, a generator. The body of the
|
---|
479 | generator function is executed by calling the generator's
|
---|
480 | \method{next()} method repeatedly until it raises an exception.
|
---|
481 |
|
---|
482 | When a \keyword{yield} statement is executed, the state of the
|
---|
483 | generator is frozen and the value of \grammartoken{expression_list} is
|
---|
484 | returned to \method{next()}'s caller. By ``frozen'' we mean that all
|
---|
485 | local state is retained, including the current bindings of local
|
---|
486 | variables, the instruction pointer, and the internal evaluation stack:
|
---|
487 | enough information is saved so that the next time \method{next()} is
|
---|
488 | invoked, the function can proceed exactly as if the \keyword{yield}
|
---|
489 | statement were just another external call.
|
---|
490 |
|
---|
491 | As of Python version 2.5, the \keyword{yield} statement is now
|
---|
492 | allowed in the \keyword{try} clause of a \keyword{try} ...\
|
---|
493 | \keyword{finally} construct. If the generator is not resumed before
|
---|
494 | it is finalized (by reaching a zero reference count or by being garbage
|
---|
495 | collected), the generator-iterator's \method{close()} method will be
|
---|
496 | called, allowing any pending \keyword{finally} clauses to execute.
|
---|
497 |
|
---|
498 | \begin{notice}
|
---|
499 | In Python 2.2, the \keyword{yield} statement is only allowed
|
---|
500 | when the \code{generators} feature has been enabled. It will always
|
---|
501 | be enabled in Python 2.3. This \code{__future__} import statement can
|
---|
502 | be used to enable the feature:
|
---|
503 |
|
---|
504 | \begin{verbatim}
|
---|
505 | from __future__ import generators
|
---|
506 | \end{verbatim}
|
---|
507 | \end{notice}
|
---|
508 |
|
---|
509 |
|
---|
510 | \begin{seealso}
|
---|
511 | \seepep{0255}{Simple Generators}
|
---|
512 | {The proposal for adding generators and the \keyword{yield}
|
---|
513 | statement to Python.}
|
---|
514 |
|
---|
515 | \seepep{0342}{Coroutines via Enhanced Generators}
|
---|
516 | {The proposal that, among other generator enhancements,
|
---|
517 | proposed allowing \keyword{yield} to appear inside a
|
---|
518 | \keyword{try} ... \keyword{finally} block.}
|
---|
519 | \end{seealso}
|
---|
520 |
|
---|
521 |
|
---|
522 | \section{The \keyword{raise} statement \label{raise}}
|
---|
523 | \stindex{raise}
|
---|
524 |
|
---|
525 | \begin{productionlist}
|
---|
526 | \production{raise_stmt}
|
---|
527 | {"raise" [\token{expression} ["," \token{expression}
|
---|
528 | ["," \token{expression}]]]}
|
---|
529 | \end{productionlist}
|
---|
530 |
|
---|
531 | If no expressions are present, \keyword{raise} re-raises the last
|
---|
532 | exception that was active in the current scope. If no exception is
|
---|
533 | active in the current scope, a \exception{TypeError} exception is
|
---|
534 | raised indicating that this is an error (if running under IDLE, a
|
---|
535 | \exception{Queue.Empty} exception is raised instead).
|
---|
536 | \index{exception}
|
---|
537 | \indexii{raising}{exception}
|
---|
538 |
|
---|
539 | Otherwise, \keyword{raise} evaluates the expressions to get three
|
---|
540 | objects, using \code{None} as the value of omitted expressions. The
|
---|
541 | first two objects are used to determine the \emph{type} and
|
---|
542 | \emph{value} of the exception.
|
---|
543 |
|
---|
544 | If the first object is an instance, the type of the exception is the
|
---|
545 | class of the instance, the instance itself is the value, and the
|
---|
546 | second object must be \code{None}.
|
---|
547 |
|
---|
548 | If the first object is a class, it becomes the type of the exception.
|
---|
549 | The second object is used to determine the exception value: If it is
|
---|
550 | an instance of the class, the instance becomes the exception value.
|
---|
551 | If the second object is a tuple, it is used as the argument list for
|
---|
552 | the class constructor; if it is \code{None}, an empty argument list is
|
---|
553 | used, and any other object is treated as a single argument to the
|
---|
554 | constructor. The instance so created by calling the constructor is
|
---|
555 | used as the exception value.
|
---|
556 |
|
---|
557 | If a third object is present and not \code{None}, it must be a
|
---|
558 | traceback\obindex{traceback} object (see section~\ref{traceback}), and
|
---|
559 | it is substituted instead of the current location as the place where
|
---|
560 | the exception occurred. If the third object is present and not a
|
---|
561 | traceback object or \code{None}, a \exception{TypeError} exception is
|
---|
562 | raised. The three-expression form of \keyword{raise} is useful to
|
---|
563 | re-raise an exception transparently in an except clause, but
|
---|
564 | \keyword{raise} with no expressions should be preferred if the
|
---|
565 | exception to be re-raised was the most recently active exception in
|
---|
566 | the current scope.
|
---|
567 |
|
---|
568 | Additional information on exceptions can be found in
|
---|
569 | section~\ref{exceptions}, and information about handling exceptions is
|
---|
570 | in section~\ref{try}.
|
---|
571 |
|
---|
572 |
|
---|
573 | \section{The \keyword{break} statement \label{break}}
|
---|
574 | \stindex{break}
|
---|
575 |
|
---|
576 | \begin{productionlist}
|
---|
577 | \production{break_stmt}
|
---|
578 | {"break"}
|
---|
579 | \end{productionlist}
|
---|
580 |
|
---|
581 | \keyword{break} may only occur syntactically nested in a \keyword{for}
|
---|
582 | or \keyword{while} loop, but not nested in a function or class definition
|
---|
583 | within that loop.
|
---|
584 | \stindex{for}
|
---|
585 | \stindex{while}
|
---|
586 | \indexii{loop}{statement}
|
---|
587 |
|
---|
588 | It terminates the nearest enclosing loop, skipping the optional
|
---|
589 | \keyword{else} clause if the loop has one.
|
---|
590 | \kwindex{else}
|
---|
591 |
|
---|
592 | If a \keyword{for} loop is terminated by \keyword{break}, the loop control
|
---|
593 | target keeps its current value.
|
---|
594 | \indexii{loop control}{target}
|
---|
595 |
|
---|
596 | When \keyword{break} passes control out of a \keyword{try} statement
|
---|
597 | with a \keyword{finally} clause, that \keyword{finally} clause is executed
|
---|
598 | before really leaving the loop.
|
---|
599 | \kwindex{finally}
|
---|
600 |
|
---|
601 |
|
---|
602 | \section{The \keyword{continue} statement \label{continue}}
|
---|
603 | \stindex{continue}
|
---|
604 |
|
---|
605 | \begin{productionlist}
|
---|
606 | \production{continue_stmt}
|
---|
607 | {"continue"}
|
---|
608 | \end{productionlist}
|
---|
609 |
|
---|
610 | \keyword{continue} may only occur syntactically nested in a \keyword{for} or
|
---|
611 | \keyword{while} loop, but not nested in a function or class definition or
|
---|
612 | \keyword{finally} statement within that loop.\footnote{It may
|
---|
613 | occur within an \keyword{except} or \keyword{else} clause. The
|
---|
614 | restriction on occurring in the \keyword{try} clause is implementor's
|
---|
615 | laziness and will eventually be lifted.}
|
---|
616 | It continues with the next cycle of the nearest enclosing loop.
|
---|
617 | \stindex{for}
|
---|
618 | \stindex{while}
|
---|
619 | \indexii{loop}{statement}
|
---|
620 | \kwindex{finally}
|
---|
621 |
|
---|
622 |
|
---|
623 | \section{The \keyword{import} statement \label{import}}
|
---|
624 | \stindex{import}
|
---|
625 | \index{module!importing}
|
---|
626 | \indexii{name}{binding}
|
---|
627 | \kwindex{from}
|
---|
628 |
|
---|
629 | \begin{productionlist}
|
---|
630 | \production{import_stmt}
|
---|
631 | {"import" \token{module} ["as" \token{name}]
|
---|
632 | ( "," \token{module} ["as" \token{name}] )*}
|
---|
633 | \productioncont{| "from" \token{module} "import" \token{identifier}
|
---|
634 | ["as" \token{name}]}
|
---|
635 | \productioncont{ ( "," \token{identifier} ["as" \token{name}] )*}
|
---|
636 | \productioncont{| "from" \token{module} "import" "(" \token{identifier}
|
---|
637 | ["as" \token{name}]}
|
---|
638 | \productioncont{ ( "," \token{identifier} ["as" \token{name}] )* [","] ")"}
|
---|
639 | \productioncont{| "from" \token{module} "import" "*"}
|
---|
640 | \production{module}
|
---|
641 | {(\token{identifier} ".")* \token{identifier}}
|
---|
642 | \end{productionlist}
|
---|
643 |
|
---|
644 | Import statements are executed in two steps: (1) find a module, and
|
---|
645 | initialize it if necessary; (2) define a name or names in the local
|
---|
646 | namespace (of the scope where the \keyword{import} statement occurs).
|
---|
647 | The first form (without \keyword{from}) repeats these steps for each
|
---|
648 | identifier in the list. The form with \keyword{from} performs step
|
---|
649 | (1) once, and then performs step (2) repeatedly.
|
---|
650 |
|
---|
651 | In this context, to ``initialize'' a built-in or extension module means to
|
---|
652 | call an initialization function that the module must provide for the purpose
|
---|
653 | (in the reference implementation, the function's name is obtained by
|
---|
654 | prepending string ``init'' to the module's name); to ``initialize'' a
|
---|
655 | Python-coded module means to execute the module's body.
|
---|
656 |
|
---|
657 | The system maintains a table of modules that have been or are being
|
---|
658 | initialized,
|
---|
659 | indexed by module name. This table is
|
---|
660 | accessible as \code{sys.modules}. When a module name is found in
|
---|
661 | this table, step (1) is finished. If not, a search for a module
|
---|
662 | definition is started. When a module is found, it is loaded. Details
|
---|
663 | of the module searching and loading process are implementation and
|
---|
664 | platform specific. It generally involves searching for a ``built-in''
|
---|
665 | module with the given name and then searching a list of locations
|
---|
666 | given as \code{sys.path}.
|
---|
667 | \withsubitem{(in module sys)}{\ttindex{modules}}
|
---|
668 | \ttindex{sys.modules}
|
---|
669 | \indexii{module}{name}
|
---|
670 | \indexii{built-in}{module}
|
---|
671 | \indexii{user-defined}{module}
|
---|
672 | \refbimodindex{sys}
|
---|
673 | \indexii{filename}{extension}
|
---|
674 | \indexiii{module}{search}{path}
|
---|
675 |
|
---|
676 | If a built-in module is found,\indexii{module}{initialization} its
|
---|
677 | built-in initialization code is executed and step (1) is finished. If
|
---|
678 | no matching file is found,
|
---|
679 | \exception{ImportError}\exindex{ImportError} is raised.
|
---|
680 | \index{code block}If a file is found, it is parsed,
|
---|
681 | yielding an executable code block. If a syntax error occurs,
|
---|
682 | \exception{SyntaxError}\exindex{SyntaxError} is raised. Otherwise, an
|
---|
683 | empty module of the given name is created and inserted in the module
|
---|
684 | table, and then the code block is executed in the context of this
|
---|
685 | module. Exceptions during this execution terminate step (1).
|
---|
686 |
|
---|
687 | When step (1) finishes without raising an exception, step (2) can
|
---|
688 | begin.
|
---|
689 |
|
---|
690 | The first form of \keyword{import} statement binds the module name in
|
---|
691 | the local namespace to the module object, and then goes on to import
|
---|
692 | the next identifier, if any. If the module name is followed by
|
---|
693 | \keyword{as}, the name following \keyword{as} is used as the local
|
---|
694 | name for the module.
|
---|
695 |
|
---|
696 | The \keyword{from} form does not bind the module name: it goes through the
|
---|
697 | list of identifiers, looks each one of them up in the module found in step
|
---|
698 | (1), and binds the name in the local namespace to the object thus found.
|
---|
699 | As with the first form of \keyword{import}, an alternate local name can be
|
---|
700 | supplied by specifying "\keyword{as} localname". If a name is not found,
|
---|
701 | \exception{ImportError} is raised. If the list of identifiers is replaced
|
---|
702 | by a star (\character{*}), all public names defined in the module are
|
---|
703 | bound in the local namespace of the \keyword{import} statement..
|
---|
704 | \indexii{name}{binding}
|
---|
705 | \exindex{ImportError}
|
---|
706 |
|
---|
707 | The \emph{public names} defined by a module are determined by checking
|
---|
708 | the module's namespace for a variable named \code{__all__}; if
|
---|
709 | defined, it must be a sequence of strings which are names defined or
|
---|
710 | imported by that module. The names given in \code{__all__} are all
|
---|
711 | considered public and are required to exist. If \code{__all__} is not
|
---|
712 | defined, the set of public names includes all names found in the
|
---|
713 | module's namespace which do not begin with an underscore character
|
---|
714 | (\character{_}). \code{__all__} should contain the entire public API.
|
---|
715 | It is intended to avoid accidentally exporting items that are not part
|
---|
716 | of the API (such as library modules which were imported and used within
|
---|
717 | the module).
|
---|
718 | \withsubitem{(optional module attribute)}{\ttindex{__all__}}
|
---|
719 |
|
---|
720 | The \keyword{from} form with \samp{*} may only occur in a module
|
---|
721 | scope. If the wild card form of import --- \samp{import *} --- is
|
---|
722 | used in a function and the function contains or is a nested block with
|
---|
723 | free variables, the compiler will raise a \exception{SyntaxError}.
|
---|
724 |
|
---|
725 | \kwindex{from}
|
---|
726 | \stindex{from}
|
---|
727 |
|
---|
728 | \strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
|
---|
729 | when the module names contains one or more dots, the module search
|
---|
730 | path is carried out differently. The sequence of identifiers up to
|
---|
731 | the last dot is used to find a ``package''\index{packages}; the final
|
---|
732 | identifier is then searched inside the package. A package is
|
---|
733 | generally a subdirectory of a directory on \code{sys.path} that has a
|
---|
734 | file \file{__init__.py}.\ttindex{__init__.py}
|
---|
735 | %
|
---|
736 | [XXX Can't be bothered to spell this out right now; see the URL
|
---|
737 | \url{http://www.python.org/doc/essays/packages.html} for more details, also
|
---|
738 | about how the module search works from inside a package.]
|
---|
739 |
|
---|
740 | The built-in function \function{__import__()} is provided to support
|
---|
741 | applications that determine which modules need to be loaded
|
---|
742 | dynamically; refer to \ulink{Built-in
|
---|
743 | Functions}{../lib/built-in-funcs.html} in the
|
---|
744 | \citetitle[../lib/lib.html]{Python Library Reference} for additional
|
---|
745 | information.
|
---|
746 | \bifuncindex{__import__}
|
---|
747 |
|
---|
748 | \subsection{Future statements \label{future}}
|
---|
749 |
|
---|
750 | A \dfn{future statement}\indexii{future}{statement} is a directive to
|
---|
751 | the compiler that a particular module should be compiled using syntax
|
---|
752 | or semantics that will be available in a specified future release of
|
---|
753 | Python. The future statement is intended to ease migration to future
|
---|
754 | versions of Python that introduce incompatible changes to the
|
---|
755 | language. It allows use of the new features on a per-module basis
|
---|
756 | before the release in which the feature becomes standard.
|
---|
757 |
|
---|
758 | \begin{productionlist}[*]
|
---|
759 | \production{future_statement}
|
---|
760 | {"from" "__future__" "import" feature ["as" name] ("," feature ["as" name])*}
|
---|
761 | \productioncont{| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])* [","] ")"}
|
---|
762 | \production{feature}{identifier}
|
---|
763 | \production{name}{identifier}
|
---|
764 | \end{productionlist}
|
---|
765 |
|
---|
766 | A future statement must appear near the top of the module. The only
|
---|
767 | lines that can appear before a future statement are:
|
---|
768 |
|
---|
769 | \begin{itemize}
|
---|
770 |
|
---|
771 | \item the module docstring (if any),
|
---|
772 | \item comments,
|
---|
773 | \item blank lines, and
|
---|
774 | \item other future statements.
|
---|
775 |
|
---|
776 | \end{itemize}
|
---|
777 |
|
---|
778 | The features recognized by Python 2.3 are \samp{generators},
|
---|
779 | \samp{division} and \samp{nested_scopes}. \samp{generators} and
|
---|
780 | \samp{nested_scopes} are redundant in 2.3 because they are always
|
---|
781 | enabled.
|
---|
782 |
|
---|
783 | A future statement is recognized and treated specially at compile
|
---|
784 | time: Changes to the semantics of core constructs are often
|
---|
785 | implemented by generating different code. It may even be the case
|
---|
786 | that a new feature introduces new incompatible syntax (such as a new
|
---|
787 | reserved word), in which case the compiler may need to parse the
|
---|
788 | module differently. Such decisions cannot be pushed off until
|
---|
789 | runtime.
|
---|
790 |
|
---|
791 | For any given release, the compiler knows which feature names have been
|
---|
792 | defined, and raises a compile-time error if a future statement contains
|
---|
793 | a feature not known to it.
|
---|
794 |
|
---|
795 | The direct runtime semantics are the same as for any import statement:
|
---|
796 | there is a standard module \module{__future__}, described later, and
|
---|
797 | it will be imported in the usual way at the time the future statement
|
---|
798 | is executed.
|
---|
799 |
|
---|
800 | The interesting runtime semantics depend on the specific feature
|
---|
801 | enabled by the future statement.
|
---|
802 |
|
---|
803 | Note that there is nothing special about the statement:
|
---|
804 |
|
---|
805 | \begin{verbatim}
|
---|
806 | import __future__ [as name]
|
---|
807 | \end{verbatim}
|
---|
808 |
|
---|
809 | That is not a future statement; it's an ordinary import statement with
|
---|
810 | no special semantics or syntax restrictions.
|
---|
811 |
|
---|
812 | Code compiled by an \keyword{exec} statement or calls to the builtin functions
|
---|
813 | \function{compile()} and \function{execfile()} that occur in a module
|
---|
814 | \module{M} containing a future statement will, by default, use the new
|
---|
815 | syntax or semantics associated with the future statement. This can,
|
---|
816 | starting with Python 2.2 be controlled by optional arguments to
|
---|
817 | \function{compile()} --- see the documentation of that function in the
|
---|
818 | \citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
|
---|
819 | details.
|
---|
820 |
|
---|
821 | A future statement typed at an interactive interpreter prompt will
|
---|
822 | take effect for the rest of the interpreter session. If an
|
---|
823 | interpreter is started with the \programopt{-i} option, is passed a
|
---|
824 | script name to execute, and the script includes a future statement, it
|
---|
825 | will be in effect in the interactive session started after the script
|
---|
826 | is executed.
|
---|
827 |
|
---|
828 | \section{The \keyword{global} statement \label{global}}
|
---|
829 | \stindex{global}
|
---|
830 |
|
---|
831 | \begin{productionlist}
|
---|
832 | \production{global_stmt}
|
---|
833 | {"global" \token{identifier} ("," \token{identifier})*}
|
---|
834 | \end{productionlist}
|
---|
835 |
|
---|
836 | The \keyword{global} statement is a declaration which holds for the
|
---|
837 | entire current code block. It means that the listed identifiers are to be
|
---|
838 | interpreted as globals. It would be impossible to assign to a global
|
---|
839 | variable without \keyword{global}, although free variables may refer
|
---|
840 | to globals without being declared global.
|
---|
841 | \indexiii{global}{name}{binding}
|
---|
842 |
|
---|
843 | Names listed in a \keyword{global} statement must not be used in the same
|
---|
844 | code block textually preceding that \keyword{global} statement.
|
---|
845 |
|
---|
846 | Names listed in a \keyword{global} statement must not be defined as formal
|
---|
847 | parameters or in a \keyword{for} loop control target, \keyword{class}
|
---|
848 | definition, function definition, or \keyword{import} statement.
|
---|
849 |
|
---|
850 | (The current implementation does not enforce the latter two
|
---|
851 | restrictions, but programs should not abuse this freedom, as future
|
---|
852 | implementations may enforce them or silently change the meaning of the
|
---|
853 | program.)
|
---|
854 |
|
---|
855 | \strong{Programmer's note:}
|
---|
856 | the \keyword{global} is a directive to the parser. It
|
---|
857 | applies only to code parsed at the same time as the \keyword{global}
|
---|
858 | statement. In particular, a \keyword{global} statement contained in an
|
---|
859 | \keyword{exec} statement does not affect the code block \emph{containing}
|
---|
860 | the \keyword{exec} statement, and code contained in an \keyword{exec}
|
---|
861 | statement is unaffected by \keyword{global} statements in the code
|
---|
862 | containing the \keyword{exec} statement. The same applies to the
|
---|
863 | \function{eval()}, \function{execfile()} and \function{compile()} functions.
|
---|
864 | \stindex{exec}
|
---|
865 | \bifuncindex{eval}
|
---|
866 | \bifuncindex{execfile}
|
---|
867 | \bifuncindex{compile}
|
---|
868 |
|
---|
869 |
|
---|
870 | \section{The \keyword{exec} statement \label{exec}}
|
---|
871 | \stindex{exec}
|
---|
872 |
|
---|
873 | \begin{productionlist}
|
---|
874 | \production{exec_stmt}
|
---|
875 | {"exec" \token{expression}
|
---|
876 | ["in" \token{expression} ["," \token{expression}]]}
|
---|
877 | \end{productionlist}
|
---|
878 |
|
---|
879 | This statement supports dynamic execution of Python code. The first
|
---|
880 | expression should evaluate to either a string, an open file object, or
|
---|
881 | a code object. If it is a string, the string is parsed as a suite of
|
---|
882 | Python statements which is then executed (unless a syntax error
|
---|
883 | occurs). If it is an open file, the file is parsed until \EOF{} and
|
---|
884 | executed. If it is a code object, it is simply executed. In all
|
---|
885 | cases, the code that's executed is expected to be valid as file
|
---|
886 | input (see section~\ref{file-input}, ``File input''). Be aware that
|
---|
887 | the \keyword{return} and \keyword{yield} statements may not be used
|
---|
888 | outside of function definitions even within the context of code passed
|
---|
889 | to the \keyword{exec} statement.
|
---|
890 |
|
---|
891 | In all cases, if the optional parts are omitted, the code is executed
|
---|
892 | in the current scope. If only the first expression after \keyword{in}
|
---|
893 | is specified, it should be a dictionary, which will be used for both
|
---|
894 | the global and the local variables. If two expressions are given,
|
---|
895 | they are used for the global and local variables, respectively.
|
---|
896 | If provided, \var{locals} can be any mapping object.
|
---|
897 | \versionchanged[formerly \var{locals} was required to be a dictionary]{2.4}
|
---|
898 |
|
---|
899 | As a side effect, an implementation may insert additional keys into
|
---|
900 | the dictionaries given besides those corresponding to variable names
|
---|
901 | set by the executed code. For example, the current implementation
|
---|
902 | may add a reference to the dictionary of the built-in module
|
---|
903 | \module{__builtin__} under the key \code{__builtins__} (!).
|
---|
904 | \ttindex{__builtins__}
|
---|
905 | \refbimodindex{__builtin__}
|
---|
906 |
|
---|
907 | \strong{Programmer's hints:}
|
---|
908 | dynamic evaluation of expressions is supported by the built-in
|
---|
909 | function \function{eval()}. The built-in functions
|
---|
910 | \function{globals()} and \function{locals()} return the current global
|
---|
911 | and local dictionary, respectively, which may be useful to pass around
|
---|
912 | for use by \keyword{exec}.
|
---|
913 | \bifuncindex{eval}
|
---|
914 | \bifuncindex{globals}
|
---|
915 | \bifuncindex{locals}
|
---|
916 |
|
---|
917 |
|
---|
918 |
|
---|