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