This commit was manufactured by cvs2svn to create tag 'r221'.
[python/dscho.git] / Doc / ref / ref6.tex
blob77104725368a3bb5f09e6c5b18b4162e2d11bd82
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 \ttindex{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_statement}
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 1 under normal circumstances, 0
88 when optimization is requested (command line option -O). The current
89 code generator emits no code for an assert statement when optimization
90 is requested at compile time. Note that it is unnecessary to include
91 the source code for the expression that failed in the error message;
92 it will be displayed as part of the stack trace.
94 Assignments to \code{__debug__} are illegal. The value for the
95 built-in variable is determined when the interpreter starts.
98 \section{Assignment statements \label{assignment}}
100 Assignment statements\indexii{assignment}{statement} are used to
101 (re)bind names to values and to modify attributes or items of mutable
102 objects:
103 \indexii{binding}{name}
104 \indexii{rebinding}{name}
105 \obindex{mutable}
106 \indexii{attribute}{assignment}
108 \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}
114 {\token{identifier}}
115 \productioncont{| "(" \token{target_list} ")"}
116 \productioncont{| "[" \token{target_list} "]"}
117 \productioncont{| \token{attributeref}}
118 \productioncont{| \token{subscription}}
119 \productioncont{| \token{slicing}}
120 \end{productionlist}
122 (See section~\ref{primaries} for the syntax definitions for the last
123 three symbols.)
125 An assignment statement evaluates the expression list (remember that
126 this can be a single expression or a comma-separated list, the latter
127 yielding a tuple) and assigns the single resulting object to each of
128 the target lists, from left to right.
129 \indexii{expression}{list}
131 Assignment is defined recursively depending on the form of the target
132 (list). When a target is part of a mutable object (an attribute
133 reference, subscription or slicing), the mutable object must
134 ultimately perform the assignment and decide about its validity, and
135 may raise an exception if the assignment is unacceptable. The rules
136 observed by various types and the exceptions raised are given with the
137 definition of the object types (see section~\ref{types}).
138 \index{target}
139 \indexii{target}{list}
141 Assignment of an object to a target list is recursively defined as
142 follows.
143 \indexiii{target}{list}{assignment}
145 \begin{itemize}
146 \item
147 If the target list is a single target: The object is assigned to that
148 target.
150 \item
151 If the target list is a comma-separated list of targets: The object
152 must be a sequence with the same number of items as the there are
153 targets in the target list, and the items are assigned, from left to
154 right, to the corresponding targets. (This rule is relaxed as of
155 Python 1.5; in earlier versions, the object had to be a tuple. Since
156 strings are sequences, an assignment like \samp{a, b = "xy"} is
157 now legal as long as the string has the right length.)
159 \end{itemize}
161 Assignment of an object to a single target is recursively defined as
162 follows.
164 \begin{itemize} % nested
166 \item
167 If the target is an identifier (name):
169 \begin{itemize}
171 \item
172 If the name does not occur in a \keyword{global} statement in the current
173 code block: the name is bound to the object in the current local
174 namespace.
175 \stindex{global}
177 \item
178 Otherwise: the name is bound to the object in the current global
179 namespace.
181 \end{itemize} % nested
183 The name is rebound if it was already bound. This may cause the
184 reference count for the object previously bound to the name to reach
185 zero, causing the object to be deallocated and its
186 destructor\index{destructor} (if it has one) to be called.
188 \item
189 If the target is a target list enclosed in parentheses or in square
190 brackets: The object must be a sequence with the same number of items
191 as there are targets in the target list, and its items are assigned,
192 from left to right, to the corresponding targets.
194 \item
195 If the target is an attribute reference: The primary expression in the
196 reference is evaluated. It should yield an object with assignable
197 attributes; if this is not the case, \exception{TypeError} is raised. That
198 object is then asked to assign the assigned object to the given
199 attribute; if it cannot perform the assignment, it raises an exception
200 (usually but not necessarily \exception{AttributeError}).
201 \indexii{attribute}{assignment}
203 \item
204 If the target is a subscription: The primary expression in the
205 reference is evaluated. It should yield either a mutable sequence
206 object (e.g., a list) or a mapping object (e.g., a dictionary). Next,
207 the subscript expression is evaluated.
208 \indexii{subscription}{assignment}
209 \obindex{mutable}
211 If the primary is a mutable sequence object (e.g., a list), the subscript
212 must yield a plain integer. If it is negative, the sequence's length
213 is added to it. The resulting value must be a nonnegative integer
214 less than the sequence's length, and the sequence is asked to assign
215 the assigned object to its item with that index. If the index is out
216 of range, \exception{IndexError} is raised (assignment to a subscripted
217 sequence cannot add new items to a list).
218 \obindex{sequence}
219 \obindex{list}
221 If the primary is a mapping object (e.g., a dictionary), the subscript must
222 have a type compatible with the mapping's key type, and the mapping is
223 then asked to create a key/datum pair which maps the subscript to
224 the assigned object. This can either replace an existing key/value
225 pair with the same key value, or insert a new key/value pair (if no
226 key with the same value existed).
227 \obindex{mapping}
228 \obindex{dictionary}
230 \item
231 If the target is a slicing: The primary expression in the reference is
232 evaluated. It should yield a mutable sequence object (e.g., a list). The
233 assigned object should be a sequence object of the same type. Next,
234 the lower and upper bound expressions are evaluated, insofar they are
235 present; defaults are zero and the sequence's length. The bounds
236 should evaluate to (small) integers. If either bound is negative, the
237 sequence's length is added to it. The resulting bounds are clipped to
238 lie between zero and the sequence's length, inclusive. Finally, the
239 sequence object is asked to replace the slice with the items of the
240 assigned sequence. The length of the slice may be different from the
241 length of the assigned sequence, thus changing the length of the
242 target sequence, if the object allows it.
243 \indexii{slicing}{assignment}
245 \end{itemize}
247 (In the current implementation, the syntax for targets is taken
248 to be the same as for expressions, and invalid syntax is rejected
249 during the code generation phase, causing less detailed error
250 messages.)
252 WARNING: Although the definition of assignment implies that overlaps
253 between the left-hand side and the right-hand side are `safe' (e.g.,
254 \samp{a, b = b, a} swaps two variables), overlaps \emph{within} the
255 collection of assigned-to variables are not safe! For instance, the
256 following program prints \samp{[0, 2]}:
258 \begin{verbatim}
259 x = [0, 1]
260 i = 0
261 i, x[i] = 1, 2
262 print x
263 \end{verbatim}
266 \subsection{Augmented assignment statements \label{augassign}}
268 Augmented assignment is the combination, in a single statement, of a binary
269 operation and an assignment statement:
270 \indexii{augmented}{assignment}
271 \index{statement!assignment, augmented}
273 \begin{productionlist}
274 \production{augmented_assignment_stmt}
275 {\token{target} \token{augop} \token{expression_list}}
276 \production{augop}
277 {"+=" | "-=" | "*=" | "/=" | "\%=" | "**="}
278 \productioncont{| ">>=" | "<<=" | "\&=" | "\textasciicircum=" | "|="}
279 \end{productionlist}
281 (See section~\ref{primaries} for the syntax definitions for the last
282 three symbols.)
284 An augmented assignment evaluates the target (which, unlike normal
285 assignment statements, cannot be an unpacking) and the expression
286 list, performs the binary operation specific to the type of assignment
287 on the two operands, and assigns the result to the original
288 target. The target is only evaluated once.
290 An augmented assignment expression like \code{x += 1} can be rewritten as
291 \code{x = x + 1} to achieve a similar, but not exactly equal effect. In the
292 augmented version, \code{x} is only evaluated once. Also, when possible, the
293 actual operation is performed \emph{in-place}, meaning that rather than
294 creating a new object and assigning that to the target, the old object is
295 modified instead.
297 With the exception of assigning to tuples and multiple targets in a single
298 statement, the assignment done by augmented assignment statements is handled
299 the same way as normal assignments. Similarly, with the exception of the
300 possible \emph{in-place} behavior, the binary operation performed by
301 augmented assignment is the same as the normal binary operations.
304 \section{The \keyword{pass} statement \label{pass}}
305 \stindex{pass}
307 \begin{productionlist}
308 \production{pass_stmt}
309 {"pass"}
310 \end{productionlist}
312 \keyword{pass} is a null operation --- when it is executed, nothing
313 happens. It is useful as a placeholder when a statement is
314 required syntactically, but no code needs to be executed, for example:
315 \indexii{null}{operation}
317 \begin{verbatim}
318 def f(arg): pass # a function that does nothing (yet)
320 class C: pass # a class with no methods (yet)
321 \end{verbatim}
324 \section{The \keyword{del} statement \label{del}}
325 \stindex{del}
327 \begin{productionlist}
328 \production{del_stmt}
329 {"del" \token{target_list}}
330 \end{productionlist}
332 Deletion is recursively defined very similar to the way assignment is
333 defined. Rather that spelling it out in full details, here are some
334 hints.
335 \indexii{deletion}{target}
336 \indexiii{deletion}{target}{list}
338 Deletion of a target list recursively deletes each target, from left
339 to right.
341 Deletion of a name removes the binding of that name (which must exist)
342 from the local or global namespace, depending on whether the name
343 occurs in a \keyword{global} statement in the same code block.
344 \stindex{global}
345 \indexii{unbinding}{name}
347 Deletion of attribute references, subscriptions and slicings
348 is passed to the primary object involved; deletion of a slicing
349 is in general equivalent to assignment of an empty slice of the
350 right type (but even this is determined by the sliced object).
351 \indexii{attribute}{deletion}
354 \section{The \keyword{print} statement \label{print}}
355 \stindex{print}
357 \begin{productionlist}
358 \production{print_stmt}
359 {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}}
360 \productioncont{| ">\code{>}" \token{expression}
361 \optional{("," \token{expression})+ \optional{","}} )}
362 \end{productionlist}
364 \keyword{print} evaluates each expression in turn and writes the
365 resulting object to standard output (see below). If an object is not
366 a string, it is first converted to a string using the rules for string
367 conversions. The (resulting or original) string is then written. A
368 space is written before each object is (converted and) written, unless
369 the output system believes it is positioned at the beginning of a
370 line. This is the case (1) when no characters have yet been written
371 to standard output, (2) when the last character written to standard
372 output is \character{\e n}, or (3) when the last write operation on
373 standard output was not a \keyword{print} statement. (In some cases
374 it may be functional to write an empty string to standard output for
375 this reason.) \note{Objects which act like file objects but which are
376 not the built-in file objects often do not properly emulate this
377 aspect of the file object's behavior, so it is best not to rely on
378 this.}
379 \index{output}
380 \indexii{writing}{values}
382 A \character{\e n} character is written at the end, unless the
383 \keyword{print} statement ends with a comma. This is the only action
384 if the statement contains just the keyword \keyword{print}.
385 \indexii{trailing}{comma}
386 \indexii{newline}{suppression}
388 Standard output is defined as the file object named \code{stdout}
389 in the built-in module \module{sys}. If no such object exists, or if
390 it does not have a \method{write()} method, a \exception{RuntimeError}
391 exception is raised.
392 \indexii{standard}{output}
393 \refbimodindex{sys}
394 \withsubitem{(in module sys)}{\ttindex{stdout}}
395 \exindex{RuntimeError}
397 \keyword{print} also has an extended\index{extended print statement}
398 form, defined by the second portion of the syntax described above.
399 This form is sometimes referred to as ``\keyword{print} chevron.''
400 In this form, the first expression after the \code{>}\code{>} must
401 evaluate to a ``file-like'' object, specifically an object that has a
402 \method{write()} method as described above. With this extended form,
403 the subsequent expressions are printed to this file object. If the
404 first expression evaluates to \code{None}, then \code{sys.stdout} is
405 used as the file for output.
408 \section{The \keyword{return} statement \label{return}}
409 \stindex{return}
411 \begin{productionlist}
412 \production{return_stmt}
413 {"return" [\token{expression_list}]}
414 \end{productionlist}
416 \keyword{return} may only occur syntactically nested in a function
417 definition, not within a nested class definition.
418 \indexii{function}{definition}
419 \indexii{class}{definition}
421 If an expression list is present, it is evaluated, else \code{None}
422 is substituted.
424 \keyword{return} leaves the current function call with the expression
425 list (or \code{None}) as return value.
427 When \keyword{return} passes control out of a \keyword{try} statement
428 with a \keyword{finally} clause, that \keyword{finally} clause is executed
429 before really leaving the function.
430 \kwindex{finally}
432 In a generator function, the \keyword{return} statement is not allowed
433 to include an \grammartoken{expression_list}. In that context, a bare
434 \keyword{return} indicates that the generator is done and will cause
435 \exception{StopIteration} to be raised.
438 \section{The \keyword{yield} statement \label{yield}}
439 \stindex{yield}
441 \begin{productionlist}
442 \production{yield_stmt}
443 {"yield" \token{expression_list}}
444 \end{productionlist}
446 \index{generator!function}
447 \index{generator!iterator}
448 \index{function!generator}
449 \exindex{StopIteration}
451 The \keyword{yield} statement is only used when defining a generator
452 function, and is only used in the body of the generator function.
453 Using a \keyword{yield} statement in a function definition is
454 sufficient to cause that definition to create a generator function
455 instead of a normal function.
457 When a generator function is called, it returns an iterator known as a
458 generator iterator, or more commonly, a generator. The body of the
459 generator function is executed by calling the generator's
460 \method{next()} method repeatedly until it raises an exception.
462 When a \keyword{yield} statement is executed, the state of the
463 generator is frozen and the value of \grammartoken{expression_list} is
464 returned to \method{next()}'s caller. By ``frozen'' we mean that all
465 local state is retained, including the current bindings of local
466 variables, the instruction pointer, and the internal evaluation stack:
467 enough information is saved so that the next time \method{next()} is
468 invoked, the function can proceed exactly as if the \keyword{yield}
469 statement were just another external call.
471 The \keyword{yield} statement is not allowed in the \keyword{try}
472 clause of a \keyword{try} ...\ \keyword{finally} construct. The
473 difficulty is that there's no guarantee the generator will ever be
474 resumed, hence no guarantee that the \keyword{finally} block will ever
475 get executed.
477 \begin{notice}
478 In Python 2.2, the \keyword{yield} statement is only allowed
479 when the \code{generators} feature has been enabled. It will always
480 be enabled in Python 2.3. This \code{__future__} import statment can
481 be used to enable the feature:
483 \begin{verbatim}
484 from __future__ import generators
485 \end{verbatim}
486 \end{notice}
489 \begin{seealso}
490 \seepep{0255}{Simple Generators}
491 {The proposal for adding generators and the \keyword{yield}
492 statement to Python.}
493 \end{seealso}
496 \section{The \keyword{raise} statement \label{raise}}
497 \stindex{raise}
499 \begin{productionlist}
500 \production{raise_stmt}
501 {"raise" [\token{expression} ["," \token{expression}
502 ["," \token{expression}]]]}
503 \end{productionlist}
505 If no expressions are present, \keyword{raise} re-raises the last
506 expression that was raised in the current scope.
508 Otherwise, \keyword{raise} evaluates its first expression, which must yield
509 a string, class, or instance object. If there is a second expression,
510 this is evaluated, else \code{None} is substituted. If the first
511 expression is a class object, then the second expression may be an
512 instance of that class or one of its derivatives, and then that
513 instance is raised. If the second expression is not such an instance,
514 the given class is instantiated. The argument list for the
515 instantiation is determined as follows: if the second expression is a
516 tuple, it is used as the argument list; if it is \code{None}, the
517 argument list is empty; otherwise, the argument list consists of a
518 single argument which is the second expression. If the first
519 expression is an instance object, the second expression must be
520 \code{None}.
521 \index{exception}
522 \indexii{raising}{exception}
524 If the first object is a string, it then raises the exception
525 identified by the first object, with the second one (or \code{None})
526 as its parameter. If the first object is a class or instance,
527 it raises the exception identified by the class of the instance
528 determined in the previous step, with the instance as
529 its parameter.
531 If a third object is present, and it is not \code{None}, it should be
532 a traceback object (see section~\ref{traceback}), and it is
533 substituted instead of the current location as the place where the
534 exception occurred. This is useful to re-raise an exception
535 transparently in an except clause.
536 \obindex{traceback}
539 \section{The \keyword{break} statement \label{break}}
540 \stindex{break}
542 \begin{productionlist}
543 \production{break_stmt}
544 {"break"}
545 \end{productionlist}
547 \keyword{break} may only occur syntactically nested in a \keyword{for}
548 or \keyword{while} loop, but not nested in a function or class definition
549 within that loop.
550 \stindex{for}
551 \stindex{while}
552 \indexii{loop}{statement}
554 It terminates the nearest enclosing loop, skipping the optional
555 \keyword{else} clause if the loop has one.
556 \kwindex{else}
558 If a \keyword{for} loop is terminated by \keyword{break}, the loop control
559 target keeps its current value.
560 \indexii{loop control}{target}
562 When \keyword{break} passes control out of a \keyword{try} statement
563 with a \keyword{finally} clause, that \keyword{finally} clause is executed
564 before really leaving the loop.
565 \kwindex{finally}
568 \section{The \keyword{continue} statement \label{continue}}
569 \stindex{continue}
571 \begin{productionlist}
572 \production{continue_stmt}
573 {"continue"}
574 \end{productionlist}
576 \keyword{continue} may only occur syntactically nested in a \keyword{for} or
577 \keyword{while} loop, but not nested in a function or class definition or
578 \keyword{try} statement within that loop.\footnote{It may
579 occur within an \keyword{except} or \keyword{else} clause. The
580 restriction on occurring in the \keyword{try} clause is implementor's
581 laziness and will eventually be lifted.}
582 It continues with the next cycle of the nearest enclosing loop.
583 \stindex{for}
584 \stindex{while}
585 \indexii{loop}{statement}
586 \kwindex{finally}
589 \section{The \keyword{import} statement \label{import}}
590 \stindex{import}
592 \begin{productionlist}
593 \production{import_stmt}
594 {"import" \token{module} ["as" \token{name}]
595 ( "," \token{module} ["as" \token{name}] )*}
596 \productioncont{| "from" \token{module} "import" \token{identifier}
597 ["as" \token{name}]}
598 \productioncont{ ( "," \token{identifier} ["as" \token{name}] )*}
599 \productioncont{| "from" \token{module} "import" "*"}
600 \production{module}
601 {(\token{identifier} ".")* \token{identifier}}
602 \end{productionlist}
604 Import statements are executed in two steps: (1) find a module, and
605 initialize it if necessary; (2) define a name or names in the local
606 namespace (of the scope where the \keyword{import} statement occurs).
607 The first form (without \keyword{from}) repeats these steps for each
608 identifier in the list. The form with \keyword{from} performs step
609 (1) once, and then performs step (2) repeatedly.
610 \indexii{importing}{module}
611 \indexii{name}{binding}
612 \kwindex{from}
613 % XXX Need to define what ``initialize'' means here
615 The system maintains a table of modules that have been initialized,
616 indexed by module name. This table is
617 accessible as \code{sys.modules}. When a module name is found in
618 this table, step (1) is finished. If not, a search for a module
619 definition is started. When a module is found, it is loaded. Details
620 of the module searching and loading process are implementation and
621 platform specific. It generally involves searching for a ``built-in''
622 module with the given name and then searching a list of locations
623 given as \code{sys.path}.
624 \withsubitem{(in module sys)}{\ttindex{modules}}
625 \ttindex{sys.modules}
626 \indexii{module}{name}
627 \indexii{built-in}{module}
628 \indexii{user-defined}{module}
629 \refbimodindex{sys}
630 \indexii{filename}{extension}
631 \indexiii{module}{search}{path}
633 If a built-in module is found, its built-in initialization code is
634 executed and step (1) is finished. If no matching file is found,
635 \exception{ImportError} is raised. If a file is found, it is parsed,
636 yielding an executable code block. If a syntax error occurs,
637 \exception{SyntaxError} is raised. Otherwise, an empty module of the given
638 name is created and inserted in the module table, and then the code
639 block is executed in the context of this module. Exceptions during
640 this execution terminate step (1).
641 \indexii{module}{initialization}
642 \exindex{SyntaxError}
643 \exindex{ImportError}
644 \index{code block}
646 When step (1) finishes without raising an exception, step (2) can
647 begin.
649 The first form of \keyword{import} statement binds the module name in
650 the local namespace to the module object, and then goes on to import
651 the next identifier, if any. If the module name is followed by
652 \keyword{as}, the name following \keyword{as} is used as the local
653 name for the module. To avoid confusion, you cannot import modules
654 with dotted names \keyword{as} a different local name. So \code{import
655 module as m} is legal, but \code{import module.submod as s} is not.
656 The latter should be written as \code{from module import submod as s};
657 see below.
659 The \keyword{from} form does not bind the module name: it goes through the
660 list of identifiers, looks each one of them up in the module found in step
661 (1), and binds the name in the local namespace to the object thus found.
662 As with the first form of \keyword{import}, an alternate local name can be
663 supplied by specifying "\keyword{as} localname". If a name is not found,
664 \exception{ImportError} is raised. If the list of identifiers is replaced
665 by a star (\character{*}), all public names defined in the module are
666 bound in the local namespace of the \keyword{import} statement..
667 \indexii{name}{binding}
668 \exindex{ImportError}
670 The \emph{public names} defined by a module are determined by checking
671 the module's namespace for a variable named \code{__all__}; if
672 defined, it must be a sequence of strings which are names defined or
673 imported by that module. The names given in \code{__all__} are all
674 considered public and are required to exist. If \code{__all__} is not
675 defined, the set of public names includes all names found in the
676 module's namespace which do not begin with an underscore character
677 (\character{_}).
679 Names bound by \keyword{import} statements may not occur in
680 \keyword{global} statements in the same scope.
681 \stindex{global}
683 The \keyword{from} form with \samp{*} may only occur in a module scope.
684 \kwindex{from}
685 \stindex{from}
687 \strong{Hierarchical module names:}\indexiii{hierarchical}{module}{names}
688 when the module names contains one or more dots, the module search
689 path is carried out differently. The sequence of identifiers up to
690 the last dot is used to find a ``package''\index{packages}; the final
691 identifier is then searched inside the package. A package is
692 generally a subdirectory of a directory on \code{sys.path} that has a
693 file \file{__init__.py}.\ttindex{__init__.py}
695 [XXX Can't be bothered to spell this out right now; see the URL
696 \url{http://www.python.org/doc/essays/packages.html} for more details, also
697 about how the module search works from inside a package.]
699 The built-in function \function{__import__()} is provided to support
700 applications that determine which modules need to be loaded
701 dynamically; refer to \ulink{Built-in
702 Functions}{../lib/built-in-funcs.html} in the
703 \citetitle[../lib/lib.html]{Python Library Reference} for additional
704 information.
705 \bifuncindex{__import__}
708 \section{The \keyword{global} statement \label{global}}
709 \stindex{global}
711 \begin{productionlist}
712 \production{global_stmt}
713 {"global" \token{identifier} ("," \token{identifier})*}
714 \end{productionlist}
716 The \keyword{global} statement is a declaration which holds for the
717 entire current code block. It means that the listed identifiers are to be
718 interpreted as globals. While \emph{using} global names is automatic
719 if they are not defined in the local scope, \emph{assigning} to global
720 names would be impossible without \keyword{global}.
721 \indexiii{global}{name}{binding}
723 Names listed in a \keyword{global} statement must not be used in the same
724 code block textually preceding that \keyword{global} statement.
726 Names listed in a \keyword{global} statement must not be defined as formal
727 parameters or in a \keyword{for} loop control target, \keyword{class}
728 definition, function definition, or \keyword{import} statement.
730 (The current implementation does not enforce the latter two
731 restrictions, but programs should not abuse this freedom, as future
732 implementations may enforce them or silently change the meaning of the
733 program.)
735 \strong{Programmer's note:}
736 the \keyword{global} is a directive to the parser. It
737 applies only to code parsed at the same time as the \keyword{global}
738 statement. In particular, a \keyword{global} statement contained in an
739 \keyword{exec} statement does not affect the code block \emph{containing}
740 the \keyword{exec} statement, and code contained in an \keyword{exec}
741 statement is unaffected by \keyword{global} statements in the code
742 containing the \keyword{exec} statement. The same applies to the
743 \function{eval()}, \function{execfile()} and \function{compile()} functions.
744 \stindex{exec}
745 \bifuncindex{eval}
746 \bifuncindex{execfile}
747 \bifuncindex{compile}
750 \section{The \keyword{exec} statement \label{exec}}
751 \stindex{exec}
753 \begin{productionlist}
754 \production{exec_stmt}
755 {"exec" \token{expression}
756 ["in" \token{expression} ["," \token{expression}]]}
757 \end{productionlist}
759 This statement supports dynamic execution of Python code. The first
760 expression should evaluate to either a string, an open file object, or
761 a code object. If it is a string, the string is parsed as a suite of
762 Python statements which is then executed (unless a syntax error
763 occurs). If it is an open file, the file is parsed until \EOF{} and
764 executed. If it is a code object, it is simply executed.
766 In all cases, if the optional parts are omitted, the code is executed
767 in the current scope. If only the first expression after \keyword{in}
768 is specified, it should be a dictionary, which will be used for both
769 the global and the local variables. If two expressions are given,
770 both must be dictionaries and they are used for the global and local
771 variables, respectively.
773 As a side effect, an implementation may insert additional keys into
774 the dictionaries given besides those corresponding to variable names
775 set by the executed code. For example, the current implementation
776 may add a reference to the dictionary of the built-in module
777 \module{__builtin__} under the key \code{__builtins__} (!).
778 \ttindex{__builtins__}
779 \refbimodindex{__builtin__}
781 \strong{Programmer's hints:}
782 dynamic evaluation of expressions is supported by the built-in
783 function \function{eval()}. The built-in functions
784 \function{globals()} and \function{locals()} return the current global
785 and local dictionary, respectively, which may be useful to pass around
786 for use by \keyword{exec}.
787 \bifuncindex{eval}
788 \bifuncindex{globals}
789 \bifuncindex{locals}
791 Also, in the current implementation, multi-line compound statements must
792 end with a newline:
793 \code{exec "for v in seq:\e{}n\e{}tprint v\e{}n"} works, but
794 \code{exec "for v in seq:\e{}n\e{}tprint v"} fails with
795 \exception{SyntaxError}.
796 \exindex{SyntaxError}