Removed defensive test in Handler.close
[python.git] / Doc / ref / ref6.tex
blobd1d23ac3a12bea5f07344434eeb6cf5a0d386c86
1 \chapter{Simple statements \label{simple}}
2 \indexii{simple}{statement}
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:
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}
27 \section{Expression statements \label{exprstmts}}
28 \indexii{expression}{statement}
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:
36 \begin{productionlist}
37 \production{expression_stmt}
38 {\token{expression_list}}
39 \end{productionlist}
41 An expression statement evaluates the expression list (which may be a
42 single expression).
43 \indexii{expression}{list}
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}
59 \section{Assert statements \label{assert}}
61 Assert statements\stindex{assert} are a convenient way to insert
62 debugging assertions\indexii{debugging}{assertions} into a program:
64 \begin{productionlist}
65 \production{assert_stmt}
66 {"assert" \token{expression} ["," \token{expression}]}
67 \end{productionlist}
69 The simple form, \samp{assert expression}, is equivalent to
71 \begin{verbatim}
72 if __debug__:
73 if not expression: raise AssertionError
74 \end{verbatim}
76 The extended form, \samp{assert expression1, expression2}, is
77 equivalent to
79 \begin{verbatim}
80 if __debug__:
81 if not expression1: raise AssertionError, expression2
82 \end{verbatim}
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.
95 Assignments to \code{__debug__} are illegal. The value for the
96 built-in variable is determined when the interpreter starts.
99 \section{Assignment statements \label{assignment}}
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}
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}
123 (See section~\ref{primaries} for the syntax definitions for the last
124 three symbols.)
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}
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}
142 Assignment of an object to a target list is recursively defined as
143 follows.
144 \indexiii{target}{list}{assignment}
146 \begin{itemize}
147 \item
148 If the target list is a single target: The object is assigned to that
149 target.
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.)
160 \end{itemize}
162 Assignment of an object to a single target is recursively defined as
163 follows.
165 \begin{itemize} % nested
167 \item
168 If the target is an identifier (name):
170 \begin{itemize}
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}
178 \item
179 Otherwise: the name is bound to the object in the current global
180 namespace.
182 \end{itemize} % nested
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.
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.
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}
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}
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}
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}
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}
246 \end{itemize}
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.)
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]}:
259 \begin{verbatim}
260 x = [0, 1]
261 i = 0
262 i, x[i] = 1, 2
263 print x
264 \end{verbatim}
267 \subsection{Augmented assignment statements \label{augassign}}
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}
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}
283 (See section~\ref{primaries} for the syntax definitions for the last
284 three symbols.)
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.
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.
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.
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:
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}
320 \section{The \keyword{pass} statement \label{pass}}
321 \stindex{pass}
323 \begin{productionlist}
324 \production{pass_stmt}
325 {"pass"}
326 \end{productionlist}
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}
333 \begin{verbatim}
334 def f(arg): pass # a function that does nothing (yet)
336 class C: pass # a class with no methods (yet)
337 \end{verbatim}
340 \section{The \keyword{del} statement \label{del}}
341 \stindex{del}
343 \begin{productionlist}
344 \production{del_stmt}
345 {"del" \token{target_list}}
346 \end{productionlist}
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}
354 Deletion of a target list recursively deletes each target, from left
355 to right.
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}
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.
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}
374 \section{The \keyword{print} statement \label{print}}
375 \stindex{print}
377 \begin{productionlist}
378 \production{print_stmt}
379 {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}}
380 \productioncont{| ">\code{>}" \token{expression}
381 \optional{("," \token{expression})+ \optional{","}} )}
382 \end{productionlist}
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}
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}
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}
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{>}\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.
428 \section{The \keyword{return} statement \label{return}}
429 \stindex{return}
431 \begin{productionlist}
432 \production{return_stmt}
433 {"return" [\token{expression_list}]}
434 \end{productionlist}
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}
441 If an expression list is present, it is evaluated, else \code{None}
442 is substituted.
444 \keyword{return} leaves the current function call with the expression
445 list (or \code{None}) as return value.
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}
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.
458 \section{The \keyword{yield} statement \label{yield}}
459 \stindex{yield}
461 \begin{productionlist}
462 \production{yield_stmt}
463 {"yield" \token{expression_list}}
464 \end{productionlist}
466 \index{generator!function}
467 \index{generator!iterator}
468 \index{function!generator}
469 \exindex{StopIteration}
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.
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.
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.
491 The \keyword{yield} statement is not allowed in the \keyword{try}
492 clause of a \keyword{try} ...\ \keyword{finally} construct. The
493 difficulty is that there's no guarantee the generator will ever be
494 resumed, hence no guarantee that the \keyword{finally} block will ever
495 get executed.
497 \begin{notice}
498 In Python 2.2, the \keyword{yield} statement is only allowed
499 when the \code{generators} feature has been enabled. It will always
500 be enabled in Python 2.3. This \code{__future__} import statement can
501 be used to enable the feature:
503 \begin{verbatim}
504 from __future__ import generators
505 \end{verbatim}
506 \end{notice}
509 \begin{seealso}
510 \seepep{0255}{Simple Generators}
511 {The proposal for adding generators and the \keyword{yield}
512 statement to Python.}
513 \end{seealso}
516 \section{The \keyword{raise} statement \label{raise}}
517 \stindex{raise}
519 \begin{productionlist}
520 \production{raise_stmt}
521 {"raise" [\token{expression} ["," \token{expression}
522 ["," \token{expression}]]]}
523 \end{productionlist}
525 If no expressions are present, \keyword{raise} re-raises the last
526 exception that was active in the current scope. If no exception is
527 active in the current scope, a \exception{TypeError} exception is
528 raised indicating that this is an error (if running under IDLE, a
529 \exception{Queue.Empty} exception is raised instead).
530 \index{exception}
531 \indexii{raising}{exception}
533 Otherwise, \keyword{raise} evaluates the expressions to get three
534 objects, using \code{None} as the value of omitted expressions. The
535 first two objects are used to determine the \emph{type} and
536 \emph{value} of the exception.
538 If the first object is an instance, the type of the exception is the
539 class of the instance, the instance itself is the value, and the
540 second object must be \code{None}.
542 If the first object is a class, it becomes the type of the exception.
543 The second object is used to determine the exception value: If it is
544 an instance of the class, the instance becomes the exception value.
545 If the second object is a tuple, it is used as the argument list for
546 the class constructor; if it is \code{None}, an empty argument list is
547 used, and any other object is treated as a single argument to the
548 constructor. The instance so created by calling the constructor is
549 used as the exception value.
551 If a third object is present and not \code{None}, it must be a
552 traceback\obindex{traceback} object (see section~\ref{traceback}), and
553 it is substituted instead of the current location as the place where
554 the exception occurred. If the third object is present and not a
555 traceback object or \code{None}, a \exception{TypeError} exception is
556 raised. The three-expression form of \keyword{raise} is useful to
557 re-raise an exception transparently in an except clause, but
558 \keyword{raise} with no expressions should be preferred if the
559 exception to be re-raised was the most recently active exception in
560 the current scope.
562 Additional information on exceptions can be found in
563 section~\ref{exceptions}, and information about handling exceptions is
564 in section~\ref{try}.
567 \section{The \keyword{break} statement \label{break}}
568 \stindex{break}
570 \begin{productionlist}
571 \production{break_stmt}
572 {"break"}
573 \end{productionlist}
575 \keyword{break} may only occur syntactically nested in a \keyword{for}
576 or \keyword{while} loop, but not nested in a function or class definition
577 within that loop.
578 \stindex{for}
579 \stindex{while}
580 \indexii{loop}{statement}
582 It terminates the nearest enclosing loop, skipping the optional
583 \keyword{else} clause if the loop has one.
584 \kwindex{else}
586 If a \keyword{for} loop is terminated by \keyword{break}, the loop control
587 target keeps its current value.
588 \indexii{loop control}{target}
590 When \keyword{break} passes control out of a \keyword{try} statement
591 with a \keyword{finally} clause, that \keyword{finally} clause is executed
592 before really leaving the loop.
593 \kwindex{finally}
596 \section{The \keyword{continue} statement \label{continue}}
597 \stindex{continue}
599 \begin{productionlist}
600 \production{continue_stmt}
601 {"continue"}
602 \end{productionlist}
604 \keyword{continue} may only occur syntactically nested in a \keyword{for} or
605 \keyword{while} loop, but not nested in a function or class definition or
606 \keyword{finally} statement within that loop.\footnote{It may
607 occur within an \keyword{except} or \keyword{else} clause. The
608 restriction on occurring in the \keyword{try} clause is implementor's
609 laziness and will eventually be lifted.}
610 It continues with the next cycle of the nearest enclosing loop.
611 \stindex{for}
612 \stindex{while}
613 \indexii{loop}{statement}
614 \kwindex{finally}
617 \section{The \keyword{import} statement \label{import}}
618 \stindex{import}
619 \index{module!importing}
620 \indexii{name}{binding}
621 \kwindex{from}
623 \begin{productionlist}
624 \production{import_stmt}
625 {"import" \token{module} ["as" \token{name}]
626 ( "," \token{module} ["as" \token{name}] )*}
627 \productioncont{| "from" \token{module} "import" \token{identifier}
628 ["as" \token{name}]}
629 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )*}
630 \productioncont{| "from" \token{module} "import" "(" \token{identifier}
631 ["as" \token{name}]}
632 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )* [","] ")"}
633 \productioncont{| "from" \token{module} "import" "*"}
634 \production{module}
635 {(\token{identifier} ".")* \token{identifier}}
636 \end{productionlist}
638 Import statements are executed in two steps: (1) find a module, and
639 initialize it if necessary; (2) define a name or names in the local
640 namespace (of the scope where the \keyword{import} statement occurs).
641 The first form (without \keyword{from}) repeats these steps for each
642 identifier in the list. The form with \keyword{from} performs step
643 (1) once, and then performs step (2) repeatedly.
645 In this context, to ``initialize'' a built-in or extension module means to
646 call an initialization function that the module must provide for the purpose
647 (in the reference implementation, the function's name is obtained by
648 prepending string ``init'' to the module's name); to ``initialize'' a
649 Python-coded module means to execute the module's body.
651 The system maintains a table of modules that have been or are being
652 initialized,
653 indexed by module name. This table is
654 accessible as \code{sys.modules}. When a module name is found in
655 this table, step (1) is finished. If not, a search for a module
656 definition is started. When a module is found, it is loaded. Details
657 of the module searching and loading process are implementation and
658 platform specific. It generally involves searching for a ``built-in''
659 module with the given name and then searching a list of locations
660 given as \code{sys.path}.
661 \withsubitem{(in module sys)}{\ttindex{modules}}
662 \ttindex{sys.modules}
663 \indexii{module}{name}
664 \indexii{built-in}{module}
665 \indexii{user-defined}{module}
666 \refbimodindex{sys}
667 \indexii{filename}{extension}
668 \indexiii{module}{search}{path}
670 If a built-in module is found,\indexii{module}{initialization} its
671 built-in initialization code is executed and step (1) is finished. If
672 no matching file is found,
673 \exception{ImportError}\exindex{ImportError} is raised.
674 \index{code block}If a file is found, it is parsed,
675 yielding an executable code block. If a syntax error occurs,
676 \exception{SyntaxError}\exindex{SyntaxError} is raised. Otherwise, an
677 empty module of the given name is created and inserted in the module
678 table, and then the code block is executed in the context of this
679 module. Exceptions during this execution terminate step (1).
681 When step (1) finishes without raising an exception, step (2) can
682 begin.
684 The first form of \keyword{import} statement binds the module name in
685 the local namespace to the module object, and then goes on to import
686 the next identifier, if any. If the module name is followed by
687 \keyword{as}, the name following \keyword{as} is used as the local
688 name for the module.
690 The \keyword{from} form does not bind the module name: it goes through the
691 list of identifiers, looks each one of them up in the module found in step
692 (1), and binds the name in the local namespace to the object thus found.
693 As with the first form of \keyword{import}, an alternate local name can be
694 supplied by specifying "\keyword{as} localname". If a name is not found,
695 \exception{ImportError} is raised. If the list of identifiers is replaced
696 by a star (\character{*}), all public names defined in the module are
697 bound in the local namespace of the \keyword{import} statement..
698 \indexii{name}{binding}
699 \exindex{ImportError}
701 The \emph{public names} defined by a module are determined by checking
702 the module's namespace for a variable named \code{__all__}; if
703 defined, it must be a sequence of strings which are names defined or
704 imported by that module. The names given in \code{__all__} are all
705 considered public and are required to exist. If \code{__all__} is not
706 defined, the set of public names includes all names found in the
707 module's namespace which do not begin with an underscore character
708 (\character{_}). \code{__all__} should contain the entire public API.
709 It is intended to avoid accidentally exporting items that are not part
710 of the API (such as library modules which were imported and used within
711 the module).
712 \withsubitem{(optional module attribute)}{\ttindex{__all__}}
714 The \keyword{from} form with \samp{*} may only occur in a module
715 scope. If the wild card form of import --- \samp{import *} --- is
716 used in a function and the function contains or is a nested block with
717 free variables, the compiler will raise a \exception{SyntaxError}.
719 \kwindex{from}
720 \stindex{from}
722 \strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
723 when the module names contains one or more dots, the module search
724 path is carried out differently. The sequence of identifiers up to
725 the last dot is used to find a ``package''\index{packages}; the final
726 identifier is then searched inside the package. A package is
727 generally a subdirectory of a directory on \code{sys.path} that has a
728 file \file{__init__.py}.\ttindex{__init__.py}
730 [XXX Can't be bothered to spell this out right now; see the URL
731 \url{http://www.python.org/doc/essays/packages.html} for more details, also
732 about how the module search works from inside a package.]
734 The built-in function \function{__import__()} is provided to support
735 applications that determine which modules need to be loaded
736 dynamically; refer to \ulink{Built-in
737 Functions}{../lib/built-in-funcs.html} in the
738 \citetitle[../lib/lib.html]{Python Library Reference} for additional
739 information.
740 \bifuncindex{__import__}
742 \subsection{Future statements \label{future}}
744 A \dfn{future statement}\indexii{future}{statement} is a directive to
745 the compiler that a particular module should be compiled using syntax
746 or semantics that will be available in a specified future release of
747 Python. The future statement is intended to ease migration to future
748 versions of Python that introduce incompatible changes to the
749 language. It allows use of the new features on a per-module basis
750 before the release in which the feature becomes standard.
752 \begin{productionlist}[*]
753 \production{future_statement}
754 {"from" "__future__" "import" feature ["as" name] ("," feature ["as" name])*}
755 \productioncont{| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])* [","] ")"}
756 \production{feature}{identifier}
757 \production{name}{identifier}
758 \end{productionlist}
760 A future statement must appear near the top of the module. The only
761 lines that can appear before a future statement are:
763 \begin{itemize}
765 \item the module docstring (if any),
766 \item comments,
767 \item blank lines, and
768 \item other future statements.
770 \end{itemize}
772 The features recognized by Python 2.3 are \samp{generators},
773 \samp{division} and \samp{nested_scopes}. \samp{generators} and
774 \samp{nested_scopes} are redundant in 2.3 because they are always
775 enabled.
777 A future statement is recognized and treated specially at compile
778 time: Changes to the semantics of core constructs are often
779 implemented by generating different code. It may even be the case
780 that a new feature introduces new incompatible syntax (such as a new
781 reserved word), in which case the compiler may need to parse the
782 module differently. Such decisions cannot be pushed off until
783 runtime.
785 For any given release, the compiler knows which feature names have been
786 defined, and raises a compile-time error if a future statement contains
787 a feature not known to it.
789 The direct runtime semantics are the same as for any import statement:
790 there is a standard module \module{__future__}, described later, and
791 it will be imported in the usual way at the time the future statement
792 is executed.
794 The interesting runtime semantics depend on the specific feature
795 enabled by the future statement.
797 Note that there is nothing special about the statement:
799 \begin{verbatim}
800 import __future__ [as name]
801 \end{verbatim}
803 That is not a future statement; it's an ordinary import statement with
804 no special semantics or syntax restrictions.
806 Code compiled by an exec statement or calls to the builtin functions
807 \function{compile()} and \function{execfile()} that occur in a module
808 \module{M} containing a future statement will, by default, use the new
809 syntax or semantics associated with the future statement. This can,
810 starting with Python 2.2 be controlled by optional arguments to
811 \function{compile()} --- see the documentation of that function in the
812 library reference for details.
814 A future statement typed at an interactive interpreter prompt will
815 take effect for the rest of the interpreter session. If an
816 interpreter is started with the \programopt{-i} option, is passed a
817 script name to execute, and the script includes a future statement, it
818 will be in effect in the interactive session started after the script
819 is executed.
821 \section{The \keyword{global} statement \label{global}}
822 \stindex{global}
824 \begin{productionlist}
825 \production{global_stmt}
826 {"global" \token{identifier} ("," \token{identifier})*}
827 \end{productionlist}
829 The \keyword{global} statement is a declaration which holds for the
830 entire current code block. It means that the listed identifiers are to be
831 interpreted as globals. It would be impossible to assign to a global
832 variable without \keyword{global}, although free variables may refer
833 to globals without being declared global.
834 \indexiii{global}{name}{binding}
836 Names listed in a \keyword{global} statement must not be used in the same
837 code block textually preceding that \keyword{global} statement.
839 Names listed in a \keyword{global} statement must not be defined as formal
840 parameters or in a \keyword{for} loop control target, \keyword{class}
841 definition, function definition, or \keyword{import} statement.
843 (The current implementation does not enforce the latter two
844 restrictions, but programs should not abuse this freedom, as future
845 implementations may enforce them or silently change the meaning of the
846 program.)
848 \strong{Programmer's note:}
849 the \keyword{global} is a directive to the parser. It
850 applies only to code parsed at the same time as the \keyword{global}
851 statement. In particular, a \keyword{global} statement contained in an
852 \keyword{exec} statement does not affect the code block \emph{containing}
853 the \keyword{exec} statement, and code contained in an \keyword{exec}
854 statement is unaffected by \keyword{global} statements in the code
855 containing the \keyword{exec} statement. The same applies to the
856 \function{eval()}, \function{execfile()} and \function{compile()} functions.
857 \stindex{exec}
858 \bifuncindex{eval}
859 \bifuncindex{execfile}
860 \bifuncindex{compile}
863 \section{The \keyword{exec} statement \label{exec}}
864 \stindex{exec}
866 \begin{productionlist}
867 \production{exec_stmt}
868 {"exec" \token{expression}
869 ["in" \token{expression} ["," \token{expression}]]}
870 \end{productionlist}
872 This statement supports dynamic execution of Python code. The first
873 expression should evaluate to either a string, an open file object, or
874 a code object. If it is a string, the string is parsed as a suite of
875 Python statements which is then executed (unless a syntax error
876 occurs). If it is an open file, the file is parsed until \EOF{} and
877 executed. If it is a code object, it is simply executed. In all
878 cases, the code that's executed is expected to be valid as file
879 input (see section~\ref{file-input}, ``File input''). Be aware that
880 the \keyword{return} and \keyword{yield} statements may not be used
881 outside of function definitions even within the context of code passed
882 to the \keyword{exec} statement.
884 In all cases, if the optional parts are omitted, the code is executed
885 in the current scope. If only the first expression after \keyword{in}
886 is specified, it should be a dictionary, which will be used for both
887 the global and the local variables. If two expressions are given,
888 they are used for the global and local variables, respectively.
889 If provided, \var{locals} can be any mapping object.
890 \versionchanged[formerly \var{locals} was required to be a dictionary]{2.4}
892 As a side effect, an implementation may insert additional keys into
893 the dictionaries given besides those corresponding to variable names
894 set by the executed code. For example, the current implementation
895 may add a reference to the dictionary of the built-in module
896 \module{__builtin__} under the key \code{__builtins__} (!).
897 \ttindex{__builtins__}
898 \refbimodindex{__builtin__}
900 \strong{Programmer's hints:}
901 dynamic evaluation of expressions is supported by the built-in
902 function \function{eval()}. The built-in functions
903 \function{globals()} and \function{locals()} return the current global
904 and local dictionary, respectively, which may be useful to pass around
905 for use by \keyword{exec}.
906 \bifuncindex{eval}
907 \bifuncindex{globals}
908 \bifuncindex{locals}