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