Finish the first pass of the language reference update.

Document extended iterable unpacking, raising and catching exceptions, class decorators, etc.
A few notable things are not documented yet, I've added XXX comments about that.
This commit is contained in:
Georg Brandl 2007-09-07 17:52:53 +00:00
parent 48952d397b
commit 02c305614d
5 changed files with 273 additions and 283 deletions

View file

@ -46,6 +46,7 @@ defining exceptions is available in the Python Tutorial under
The following exceptions are only used as base classes for other exceptions.
.. XXX document with_traceback()
.. exception:: BaseException

View file

@ -14,8 +14,10 @@ statement may be contained in one line.
The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement
traditional control flow constructs. :keyword:`try` specifies exception
handlers and/or cleanup code for a group of statements. Function and class
definitions are also syntactically compound statements.
handlers and/or cleanup code for a group of statements, while the
:keyword:`with` statement allows the execution of initialization and
finalization code around a block of code. Function and class definitions are
also syntactically compound statements.
.. index::
single: clause
@ -30,7 +32,7 @@ statements on the same line as the header, following the header's colon, or it
can be one or more indented statements on subsequent lines. Only the latter
form of suite can contain nested compound statements; the following is illegal,
mostly because it wouldn't be clear to which :keyword:`if` clause a following
:keyword:`else` clause would belong: ::
:keyword:`else` clause would belong::
if test1: if test2: print(x)
@ -60,7 +62,7 @@ Summarizing:
pair: dangling; else
Note that statements always end in a ``NEWLINE`` possibly followed by a
``DEDENT``. Also note that optional continuation clauses always begin with a
``DEDENT``. Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
'dangling :keyword:`else`' problem is solved in Python by requiring nested
:keyword:`if` statements to be indented).
@ -75,6 +77,8 @@ The :keyword:`if` statement
===========================
.. index:: statement: if
keyword: elif
keyword: else
The :keyword:`if` statement is used for conditional execution:
@ -83,10 +87,6 @@ The :keyword:`if` statement is used for conditional execution:
: ( "elif" `expression` ":" `suite` )*
: ["else" ":" `suite`]
.. index::
keyword: elif
keyword: else
It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section :ref:`booleans` for the definition of
true and false); then that suite is executed (and no other part of the
@ -101,6 +101,7 @@ The :keyword:`while` statement
.. index::
statement: while
keyword: else
pair: loop; statement
The :keyword:`while` statement is used for repeated execution as long as an
@ -110,8 +111,6 @@ expression is true:
while_stmt: "while" `expression` ":" `suite`
: ["else" ":" `suite`]
.. index:: keyword: else
This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the :keyword:`else` clause, if present, is executed and the loop
@ -134,9 +133,11 @@ The :keyword:`for` statement
.. index::
statement: for
keyword: in
keyword: else
pair: target; list
pair: loop; statement
.. index:: object: sequence
object: sequence
The :keyword:`for` statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
@ -145,17 +146,13 @@ The :keyword:`for` statement is used to iterate over the elements of a sequence
for_stmt: "for" `target_list` "in" `expression_list` ":" `suite`
: ["else" ":" `suite`]
.. index::
keyword: in
keyword: else
pair: target; list
The expression list is evaluated once; it should yield an iterable object. An
iterator is created for the result of the ``expression_list``. The suite is
then executed once for each item provided by the iterator, in the order of
ascending indices. Each item in turn is assigned to the target list using the
standard rules for assignments, and then the suite is executed. When the items
are exhausted (which is immediately when the sequence is empty), the suite in
standard rules for assignments (see :ref:`assignment`), and then the suite is
executed. When the items are exhausted (which is immediately when the sequence
is empty or an iterator raises a :exc:`StopIteration` exception), the suite in
the :keyword:`else` clause, if present, is executed, and the loop terminates.
.. index::
@ -173,13 +170,12 @@ the next item assigned to it.
.. index::
builtin: range
pair: Pascal; language
The target list is not deleted when the loop is finished, but if the sequence is
empty, it will not have been assigned to at all by the loop. Hint: the built-in
function :func:`range` returns a sequence of integers suitable to emulate the
effect of Pascal's ``for i := a to b do``; e.g., ``range(3)`` returns the list
``[0, 1, 2]``.
Names in the target list are not deleted when the loop is finished, but if the
sequence is empty, it will not have been assigned to at all by the loop. Hint:
the built-in function :func:`range` returns an iterator of integers suitable to
emulate the effect of Pascal's ``for i := a to b do``; e.g., ``range(3)``
returns the list ``[0, 1, 2]``.
.. warning::
@ -188,21 +184,19 @@ effect of Pascal's ``for i := a to b do``; e.g., ``range(3)`` returns the list
single: mutable sequence; loop over
There is a subtlety when the sequence is being modified by the loop (this can
only occur for mutable sequences, i.e. lists). An internal counter is used to
keep track of which item is used next, and this is incremented on each
only occur for mutable sequences, i.e. lists). An internal counter is used
to keep track of which item is used next, and this is incremented on each
iteration. When this counter has reached the length of the sequence the loop
terminates. This means that if the suite deletes the current (or a previous)
item from the sequence, the next item will be skipped (since it gets the index
of the current item which has already been treated). Likewise, if the suite
inserts an item in the sequence before the current item, the current item will
be treated again the next time through the loop. This can lead to nasty bugs
that can be avoided by making a temporary copy using a slice of the whole
sequence, e.g.,
item from the sequence, the next item will be skipped (since it gets the
index of the current item which has already been treated). Likewise, if the
suite inserts an item in the sequence before the current item, the current
item will be treated again the next time through the loop. This can lead to
nasty bugs that can be avoided by making a temporary copy using a slice of
the whole sequence, e.g., ::
::
for x in a[:]:
if x < 0: a.remove(x)
for x in a[:]:
if x < 0: a.remove(x)
.. _try:
@ -245,12 +239,33 @@ the new exception in the surrounding code and on the call stack (it is treated
as if the entire :keyword:`try` statement raised the exception).
When a matching except clause is found, the exception is assigned to the target
specified after the ``as`` keyword in that except clause, if present, and the
except clause's suite is executed. All except clauses must have an executable
block. When the end of this block is reached, execution continues normally
after the entire try statement. (This means that if two nested handlers exist
for the same exception, and the exception occurs in the try clause of the inner
handler, the outer handler will not handle the exception.)
specified after the :keyword:`as` keyword in that except clause, if present, and
the except clause's suite is executed. All except clauses must have an
executable block. When the end of this block is reached, execution continues
normally after the entire try statement. (This means that if two nested
handlers exist for the same exception, and the exception occurs in the try
clause of the inner handler, the outer handler will not handle the exception.)
When an exception has been assigned using ``as target``, it is cleared at the
end of the except clause. This is as if ::
except E as N:
foo
was translated to ::
except E as N:
try:
foo
finally:
N = None
del N
That means that you have to assign the exception to a different name if you want
to be able to refer to it after the except clause. The reason for this is that
with the traceback attached to them, exceptions will form a reference cycle with
the stack frame, keeping all locals in that frame alive until the next garbage
collection occurs.
.. index::
module: sys
@ -258,12 +273,12 @@ handler, the outer handler will not handle the exception.)
Before an except clause's suite is executed, details about the exception are
stored in the :mod:`sys` module and can be access via :func:`sys.exc_info`.
:func:`sys.exc_info` returns a 3-tuple consisting of: ``exc_type`` receives the
object identifying the exception; ``exc_value`` receives the exception's
parameter; ``exc_traceback`` receives a traceback object (see section
:ref:`types`) identifying the point in the program where the exception
occurred. :func:`sys.exc_info` values are restored to their previous values
(before the call) when returning from a function that handled an exception.
:func:`sys.exc_info` returns a 3-tuple consisting of: ``exc_type``, the
exception class; ``exc_value``, the exception instance; ``exc_traceback``, a
traceback object (see section :ref:`types`) identifying the point in the program
where the exception occurred. :func:`sys.exc_info` values are restored to their
previous values (before the call) when returning from a function that handled an
exception.
.. index::
keyword: else
@ -303,6 +318,12 @@ Additional information on exceptions can be found in section :ref:`exceptions`,
and information on using the :keyword:`raise` statement to generate exceptions
may be found in section :ref:`raise`.
.. seealso::
:pep:`3110` - Catching exceptions in Python 3000
Describes the differences in :keyword:`try` statements between Python 2.x
and 3.0.
.. _with:
@ -312,9 +333,9 @@ The :keyword:`with` statement
.. index:: statement: with
The :keyword:`with` statement is used to wrap the execution of a block with
methods defined by a context manager (see section :ref:`context-managers`). This
allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` usage
patterns to be encapsulated for convenient reuse.
methods defined by a context manager (see section :ref:`context-managers`).
This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally`
usage patterns to be encapsulated for convenient reuse.
.. productionlist::
with_stmt: "with" `expression` ["as" `target`] ":" `suite`
@ -330,35 +351,27 @@ The execution of the :keyword:`with` statement proceeds as follows:
.. note::
The :keyword:`with` statement guarantees that if the :meth:`__enter__` method
returns without an error, then :meth:`__exit__` will always be called. Thus, if
an error occurs during the assignment to the target list, it will be treated the
same as an error occurring within the suite would be. See step 5 below.
The :keyword:`with` statement guarantees that if the :meth:`__enter__`
method returns without an error, then :meth:`__exit__` will always be
called. Thus, if an error occurs during the assignment to the target
list, it will be treated the same as an error occurring within the suite
would be. See step 5 below.
#. The suite is executed.
#. The context manager's :meth:`__exit__` method is invoked. If an exception
#. The context manager's :meth:`__exit__` method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are passed as
arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are
supplied.
If the suite was exited due to an exception, and the return value from the
:meth:`__exit__` method was false, the exception is reraised. If the return
:meth:`__exit__` method was false, the exception is reraised. If the return
value was true, the exception is suppressed, and execution continues with the
statement following the :keyword:`with` statement.
If the suite was exited for any reason other than an exception, the return value
from :meth:`__exit__` is ignored, and execution proceeds at the normal location
for the kind of exit that was taken.
.. note::
In Python 2.5, the :keyword:`with` statement is only allowed when the
``with_statement`` feature has been enabled. It will always be enabled in
Python 2.6. This ``__future__`` import statement can be used to enable the
feature::
from __future__ import with_statement
If the suite was exited for any reason other than an exception, the return
value from :meth:`__exit__` is ignored, and execution proceeds at the normal
location for the kind of exit that was taken.
.. seealso::
@ -376,10 +389,10 @@ Function definitions
.. index::
pair: function; definition
statement: def
.. index::
object: user-defined function
object: function
pair: function; name
pair: name; binding
A function definition defines a user-defined function object (see section
:ref:`types`):
@ -398,9 +411,6 @@ A function definition defines a user-defined function object (see section
defparameter: `parameter` ["=" `expression`]
funcname: `identifier`
.. index::
pair: function; name
pair: name; binding
A function definition is an executable statement. Its execution binds the
function name in the current local namespace to a function object (a wrapper
@ -416,13 +426,13 @@ Decorator expressions are evaluated when the function is defined, in the scope
that contains the function definition. The result must be a callable, which is
invoked with the function object as the only argument. The returned value is
bound to the function name instead of the function object. Multiple decorators
are applied in nested fashion. For example, the following code::
are applied in nested fashion. For example, the following code ::
@f1(arg)
@f2
def func(): pass
is equivalent to::
is equivalent to ::
def func(): pass
func = f1(arg)(f2(func))
@ -433,16 +443,16 @@ When one or more parameters have the form *parameter* ``=`` *expression*, the
function is said to have "default parameter values." For a parameter with a
default value, the corresponding argument may be omitted from a call, in which
case the parameter's default value is substituted. If a parameter has a default
value, all following parameters up until the "``*``" must also have a default
value --- this is a syntactic restriction that is not expressed by the grammar.
value, all following parameters up until the "``*``" must also have a default
value --- this is a syntactic restriction that is not expressed by the grammar.
**Default parameter values are evaluated when the function definition is
executed.** This means that the expression is evaluated once, when the function
executed.** This means that the expression is evaluated once, when the function
is defined, and that that same "pre-computed" value is used for each call. This
is especially important to understand when a default parameter is a mutable
object, such as a list or a dictionary: if the function modifies the object
(e.g. by appending an item to a list), the default value is in effect modified.
This is generally not what was intended. A way around this is to use ``None``
This is generally not what was intended. A way around this is to use ``None``
as the default, and explicitly test for it in the body of the function, e.g.::
def whats_on_the_telly(penguin=None):
@ -451,7 +461,7 @@ as the default, and explicitly test for it in the body of the function, e.g.::
penguin.append("property of the zoo")
return penguin
Function call semantics are described in more detail in section :ref:`calls`. A
Function call semantics are described in more detail in section :ref:`calls`. A
function call always assigns values to all parameters mentioned in the parameter
list, either from position arguments, from keyword arguments, or from default
values. If the form "``*identifier``" is present, it is initialized to a tuple
@ -464,13 +474,13 @@ may only be passed used keyword arguments.
.. index:: pair: function; annotations
Parameters may have annotations of the form "``: expression``" following the
parameter name. Any parameter may have an annotation even those of the form
``*identifier`` or ``**identifier``. Functions may have "return" annotation of
the form "``-> expression``" after the parameter list. These annotations can be
parameter name. Any parameter may have an annotation even those of the form
``*identifier`` or ``**identifier``. Functions may have "return" annotation of
the form "``-> expression``" after the parameter list. These annotations can be
any valid Python expression and are evaluated when the function definition is
executed. Annotations may be evaluated in a different order than they appear in
the source code. The presence of annotations does not change the semantics of a
function. The annotation values are available as values of a dictionary keyed
executed. Annotations may be evaluated in a different order than they appear in
the source code. The presence of annotations does not change the semantics of a
function. The annotation values are available as values of a dictionary keyed
by the parameters' names in the :attr:`__annotations__` attribute of the
function object.
@ -499,22 +509,22 @@ Class definitions
.. index::
pair: class; definition
statement: class
.. index:: object: class
A class definition defines a class object (see section :ref:`types`):
.. productionlist::
classdef: "class" `classname` [`inheritance`] ":" `suite`
inheritance: "(" [`expression_list`] ")"
classname: `identifier`
.. index::
object: class
single: inheritance
pair: class; name
pair: name; binding
pair: execution; frame
A class definition defines a class object (see section :ref:`types`):
.. XXX need to document PEP 3115 changes here (new metaclasses)
.. productionlist::
classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite`
inheritance: "(" [`expression_list`] ")"
classname: `identifier`
A class definition is an executable statement. It first evaluates the
inheritance list, if present. Each item in the inheritance list should evaluate
to a class object or class type which allows subclassing. The class's suite is
@ -526,6 +536,17 @@ class object is then created using the inheritance list for the base classes and
the saved local namespace for the attribute dictionary. The class name is bound
to this class object in the original local namespace.
Classes can also be decorated; as with functions, ::
@f1(arg)
@f2
class Foo: pass
is equivalent to ::
class Foo: pass
Foo = f1(arg)(f2(Foo))
**Programmer's note:** Variables defined in the class definition are class
variables; they are shared by all instances. To define instance variables, they
must be given a value in the :meth:`__init__` method or in another method. Both
@ -537,6 +558,12 @@ instance variables with different implementation details.
.. XXX add link to descriptor docs above
.. seealso::
:pep:`3129` - Class Decorators
.. rubric:: Footnotes
.. [#] The exception is propogated to the invocation stack only if there is no

View file

@ -183,6 +183,9 @@ by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
nesting from left to right, and evaluating the expression to produce an element
each time the innermost block is reached.
Note that the comprehension is executed in a separate scope, so names assigned
to in the target list don't "leak" in the enclosing scope.
.. _lists:
@ -340,6 +343,12 @@ suspended. The only difference is that a generator function cannot control
where should the execution continue after it yields; the control is always
transfered to the generator's caller.
The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
:keyword:`try` ... :keyword:`finally` construct. If the generator is not
resumed before it is finalized (by reaching a zero reference count or by being
garbage collected), the generator-iterator's :meth:`close` method will be
called, allowing any pending :keyword:`finally` clauses to execute.
.. index:: object: generator
The following generator's methods can be used to control the execution of a
@ -428,6 +437,9 @@ generator functions::
.. seealso::
:pep:`0255` - Simple Generators
The proposal for adding generators and the :keyword:`yield` statement to Python.
:pep:`0342` - Coroutines via Enhanced Generators
The proposal to enhance the API and syntax of generators, making them
usable as simple coroutines.

View file

@ -25,6 +25,7 @@ simple statements is:
: | `continue_stmt`
: | `import_stmt`
: | `global_stmt`
: | `nonlocal_stmt`
.. _exprstmts:
@ -33,6 +34,7 @@ Expression statements
=====================
.. index:: pair: expression; statement
.. index:: pair: expression; list
Expression statements are used (mostly interactively) to compute and write a
value, or (usually) to call a procedure (a function that returns no meaningful
@ -43,8 +45,6 @@ expression statement is:
.. productionlist::
expression_stmt: `expression_list`
.. index:: pair: expression; list
An expression statement evaluates the expression list (which may be a single
expression).
@ -59,9 +59,8 @@ expression).
In interactive mode, if the value is not ``None``, it is converted to a string
using the built-in :func:`repr` function and the resulting string is written to
standard output (see :func:`print`) on a line by itself. (Expression
statements yielding ``None`` are not written, so that procedure calls do not
cause any output.)
standard output on a line by itself (except if the result is ``None``, so that
procedure calls do not cause any output.)
.. _assert:
@ -72,6 +71,8 @@ Assert statements
.. index::
statement: assert
pair: debugging; assertions
single: __debug__
exception: AssertionError
Assert statements are a convenient way to insert debugging assertions into a
program:
@ -87,23 +88,19 @@ The simple form, ``assert expression``, is equivalent to ::
The extended form, ``assert expression1, expression2``, is equivalent to ::
if __debug__:
if not expression1: raise AssertionError, expression2
if not expression1: raise AssertionError(expression2)
.. index::
single: __debug__
exception: AssertionError
These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to
the built-in variables with those names. In the current implementation, the
built-in variable ``__debug__`` is ``True`` under normal circumstances,
``False`` when optimization is requested (command line option -O). The current
code generator emits no code for an assert statement when optimization is
requested at compile time. Note that it is unnecessary to include the source
These equivalences assume that :data:`__debug__` and :exc:`AssertionError` refer
to the built-in variables with those names. In the current implementation, the
built-in variable :data:`__debug__` is ``True`` under normal circumstances,
``False`` when optimization is requested (command line option ``-O``). The
current code generator emits no code for an assert statement when optimization
is requested at compile time. Note that it is unnecessary to include the source
code for the expression that failed in the error message; it will be displayed
as part of the stack trace.
Assignments to ``__debug__`` are illegal. The value for the built-in variable
is determined when the interpreter starts.
Assignments to :data:`__debug__` are illegal. The value for the built-in
variable is determined when the interpreter starts.
.. _assignment:
@ -130,12 +127,11 @@ attributes or items of mutable objects:
: | `attributeref`
: | `subscription`
: | `slicing`
: | "*" `target`
(See section :ref:`primaries` for the syntax definitions for the last three
symbols.)
.. index:: pair: expression; list
An assignment statement evaluates the expression list (remember that this can be
a single expression or a comma-separated list, the latter yielding a tuple) and
assigns the single resulting object to each of the target lists, from left to
@ -154,48 +150,45 @@ given with the definition of the object types (see section :ref:`types`).
.. index:: triple: target; list; assignment
Assignment of an object to a target list is recursively defined as follows.
Assignment of an object to a target list, optionally enclosed in parentheses or
square brackets, is recursively defined as follows.
* If the target list is a single target: The object is assigned to that target.
* If the target list is a comma-separated list of targets: The object must be a
sequence with the same number of items as there are targets in the target list,
and the items are assigned, from left to right, to the corresponding targets.
(This rule is relaxed as of Python 1.5; in earlier versions, the object had to
be a tuple. Since strings are sequences, an assignment like ``a, b = "xy"`` is
now legal as long as the string has the right length.)
* If the target list is a comma-separated list of targets:
* If the target list contains one target prefixed with an asterisk, called a
"starred" target: The object must be a sequence with at least as many items
as there are targets in the target list, minus one. The first items of the
sequence are assigned, from left to right, to the targets before the starred
target. The final items of the sequence are assigned to the targets after
the starred target. A list of the remaining items in the sequence is then
assigned to the starred target (the list can be empty).
* Else: The object must be a sequence with the same number of items as there
are targets in the target list, and the items are assigned, from left to
right, to the corresponding targets.
Assignment of an object to a single target is recursively defined as follows.
* If the target is an identifier (name):
.. index:: statement: global
* If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
statement in the current code block: the name is bound to the object in the
current local namespace.
* If the name does not occur in a :keyword:`global` statement in the current
code block: the name is bound to the object in the current local namespace.
* Otherwise: the name is bound to the object in the global namespace or the
outer namespace determined by :keyword:`nonlocal`, respectively.
* Otherwise: the name is bound to the object in the current global namespace.
.. index:: single: destructor
The name is rebound if it was already bound. This may cause the reference count
for the object previously bound to the name to reach zero, causing the object to
be deallocated and its destructor (if it has one) to be called.
.. % nested
* If the target is a target list enclosed in parentheses or in square brackets:
The object must be a sequence with the same number of items as there are targets
in the target list, and its items are assigned, from left to right, to the
corresponding targets.
.. index:: pair: attribute; assignment
The name is rebound if it was already bound. This may cause the reference
count for the object previously bound to the name to reach zero, causing the
object to be deallocated and its destructor (if it has one) to be called.
* If the target is an attribute reference: The primary expression in the
reference is evaluated. It should yield an object with assignable attributes;
if this is not the case, :exc:`TypeError` is raised. That object is then asked
to assign the assigned object to the given attribute; if it cannot perform the
assignment, it raises an exception (usually but not necessarily
if this is not the case, :exc:`TypeError` is raised. That object is then
asked to assign the assigned object to the given attribute; if it cannot
perform the assignment, it raises an exception (usually but not necessarily
:exc:`AttributeError`).
.. index::
@ -203,20 +196,20 @@ Assignment of an object to a single target is recursively defined as follows.
object: mutable
* If the target is a subscription: The primary expression in the reference is
evaluated. It should yield either a mutable sequence object (such as a list) or
a mapping object (such as a dictionary). Next, the subscript expression is
evaluated. It should yield either a mutable sequence object (such as a list)
or a mapping object (such as a dictionary). Next, the subscript expression is
evaluated.
.. index::
object: sequence
object: list
If the primary is a mutable sequence object (such as a list), the subscript must
yield a plain integer. If it is negative, the sequence's length is added to it.
The resulting value must be a nonnegative integer less than the sequence's
length, and the sequence is asked to assign the assigned object to its item with
that index. If the index is out of range, :exc:`IndexError` is raised
(assignment to a subscripted sequence cannot add new items to a list).
If the primary is a mutable sequence object (such as a list), the subscript
must yield an integer. If it is negative, the sequence's length is added to
it. The resulting value must be a nonnegative integer less than the
sequence's length, and the sequence is asked to assign the assigned object to
its item with that index. If the index is out of range, :exc:`IndexError` is
raised (assignment to a subscripted sequence cannot add new items to a list).
.. index::
object: mapping
@ -228,19 +221,22 @@ Assignment of an object to a single target is recursively defined as follows.
object. This can either replace an existing key/value pair with the same key
value, or insert a new key/value pair (if no key with the same value existed).
For user-defined objects, the :meth:`__setitem__` method is called with
appropriate arguments.
.. index:: pair: slicing; assignment
* If the target is a slicing: The primary expression in the reference is
evaluated. It should yield a mutable sequence object (such as a list). The
assigned object should be a sequence object of the same type. Next, the lower
and upper bound expressions are evaluated, insofar they are present; defaults
are zero and the sequence's length. The bounds should evaluate to (small)
integers. If either bound is negative, the sequence's length is added to it.
The resulting bounds are clipped to lie between zero and the sequence's length,
inclusive. Finally, the sequence object is asked to replace the slice with the
items of the assigned sequence. The length of the slice may be different from
the length of the assigned sequence, thus changing the length of the target
sequence, if the object allows it.
are zero and the sequence's length. The bounds should evaluate to integers.
If either bound is negative, the sequence's length is added to it. The
resulting bounds are clipped to lie between zero and the sequence's length,
inclusive. Finally, the sequence object is asked to replace the slice with
the items of the assigned sequence. The length of the slice may be different
from the length of the assigned sequence, thus changing the length of the
target sequence, if the object allows it.
(In the current implementation, the syntax for targets is taken to be the same
as for expressions, and invalid syntax is rejected during the code generation
@ -257,6 +253,12 @@ are not safe! For instance, the following program prints ``[0, 2]``::
print(x)
.. seealso::
:pep:`3132` - Extended Iterable Unpacking
The specification for the ``*target`` feature.
.. _augassign:
Augmented assignment statements
@ -312,12 +314,11 @@ The :keyword:`pass` statement
=============================
.. index:: statement: pass
pair: null; operation
.. productionlist::
pass_stmt: "pass"
.. index:: pair: null; operation
:keyword:`pass` is a null operation --- when it is executed, nothing happens.
It is useful as a placeholder when a statement is required syntactically, but no
code needs to be executed, for example::
@ -333,14 +334,12 @@ The :keyword:`del` statement
============================
.. index:: statement: del
pair: deletion; target
triple: deletion; target; list
.. productionlist::
del_stmt: "del" `target_list`
.. index::
pair: deletion; target
triple: deletion; target; list
Deletion is recursively defined very similar to the way assignment is defined.
Rather that spelling it out in full details, here are some hints.
@ -350,7 +349,7 @@ Deletion of a target list recursively deletes each target, from left to right.
statement: global
pair: unbinding; name
Deletion of a name removes the binding of that name from the local or global
Deletion of a name removes the binding of that name from the local or global
namespace, depending on whether the name occurs in a :keyword:`global` statement
in the same code block. If the name is unbound, a :exc:`NameError` exception
will be raised.
@ -374,14 +373,12 @@ The :keyword:`return` statement
===============================
.. index:: statement: return
pair: function; definition
pair: class; definition
.. productionlist::
return_stmt: "return" [`expression_list`]
.. index::
pair: function; definition
pair: class; definition
:keyword:`return` may only occur syntactically nested in a function definition,
not within a nested class definition.
@ -407,59 +404,11 @@ raised.
The :keyword:`yield` statement
==============================
.. index:: statement: yield
.. productionlist::
yield_stmt: `yield_expression`
.. index::
single: generator; function
single: generator; iterator
single: function; generator
exception: StopIteration
The :keyword:`yield` statement is only used when defining a generator function,
and is only used in the body of the generator function. Using a :keyword:`yield`
statement in a function definition is sufficient to cause that definition to
create a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as a generator
iterator, or more commonly, a generator. The body of the generator function is
executed by calling the generator's :meth:`__next__` method repeatedly until it
raises an exception.
When a :keyword:`yield` statement is executed, the state of the generator is
frozen and the value of :token:`expression_list` is returned to
:meth:`__next__`'s caller. By "frozen" we mean that all local state is
retained, including the current bindings of local variables, the instruction
pointer, and the internal evaluation stack: enough information is saved so that
the next time :meth:`__next__` is invoked, the function can proceed exactly as
if the :keyword:`yield` statement were just another external call.
As of Python version 2.5, the :keyword:`yield` statement is now allowed in the
:keyword:`try` clause of a :keyword:`try` ... :keyword:`finally` construct. If
the generator is not resumed before it is finalized (by reaching a zero
reference count or by being garbage collected), the generator-iterator's
:meth:`close` method will be called, allowing any pending :keyword:`finally`
clauses to execute.
.. note::
In Python 2.2, the :keyword:`yield` statement is only allowed when the
``generators`` feature has been enabled. It will always be enabled in Python
2.3. This ``__future__`` import statement can be used to enable the feature::
from __future__ import generators
.. seealso::
:pep:`0255` - Simple Generators
The proposal for adding generators and the :keyword:`yield` statement to Python.
:pep:`0342` - Coroutines via Enhanced Generators
The proposal that, among other generator enhancements, proposed allowing
:keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.
The yield statement is nothing but a yield expression used as a statement,
see :ref:`yieldexpr`.
.. _raise:
@ -468,49 +417,45 @@ The :keyword:`raise` statement
==============================
.. index:: statement: raise
pair: raising; exception
.. productionlist::
raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]]
.. index::
single: exception
pair: raising; exception
raise_stmt: "raise" [`expression` ["from" `expression`]]
If no expressions are present, :keyword:`raise` re-raises the last exception
that was active in the current scope. If no exception is active in the current
scope, a :exc:`TypeError` exception is raised indicating that this is an error
(if running under IDLE, a :exc:`Queue.Empty` exception is raised instead).
Otherwise, :keyword:`raise` evaluates the expressions to get three objects,
using ``None`` as the value of omitted expressions. The first two objects are
used to determine the *type* and *value* of the exception.
Otherwise, :keyword:`raise` evaluates the first expression as the exception
object. It must be either a subclass or an instance of :class:`BaseException`.
If it is a class, the exception instance will be obtained when needed by
instantiating the class with no arguments.
If the first object is an instance, the type of the exception is the class of
the instance, the instance itself is the value, and the second object must be
``None``.
If the first object is a class, it becomes the type of the exception. The second
object is used to determine the exception value: If it is an instance of the
class, the instance becomes the exception value. If the second object is a
tuple, it is used as the argument list for the class constructor; if it is
``None``, an empty argument list is used, and any other object is treated as a
single argument to the constructor. The instance so created by calling the
constructor is used as the exception value.
The :dfn:`type` of the exception is the exception instance's class, the
:dfn:`value` is the instance itself.
.. index:: object: traceback
If a third object is present and not ``None``, it must be a traceback object
(see section :ref:`types`), and it is substituted instead of the current
location as the place where the exception occurred. If the third object is
present and not a traceback object or ``None``, a :exc:`TypeError` exception is
raised. The three-expression form of :keyword:`raise` is useful to re-raise an
exception transparently in an except clause, but :keyword:`raise` with no
expressions should be preferred if the exception to be re-raised was the most
recently active exception in the current scope.
A traceback object is normally created automatically when an exception is raised
and attached to it as the :attr:`__traceback__` attribute; however, you can set
your own traceback using the :meth:`with_traceback` exception method, like so::
raise RuntimeError("foo occurred").with_traceback(tracebackobj)
.. XXX document exception chaining
The "from" clause is used for exception chaining, which is not documented yet.
Additional information on exceptions can be found in section :ref:`exceptions`,
and information about handling exceptions is in section :ref:`try`.
.. seealso::
:pep:`3109` - Raising exceptions in Python 3000
Describes the differences in :keyword:`raise` statements between Python
2.x and 3.0.
.. _break:
@ -518,26 +463,23 @@ The :keyword:`break` statement
==============================
.. index:: statement: break
statement: for
statement: while
pair: loop; statement
.. productionlist::
break_stmt: "break"
.. index::
statement: for
statement: while
pair: loop; statement
:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
:keyword:`while` loop, but not nested in a function or class definition within
that loop.
.. index:: keyword: else
pair: loop control; target
It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
clause if the loop has one.
.. index:: pair: loop control; target
If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
target keeps its current value.
@ -554,16 +496,14 @@ The :keyword:`continue` statement
=================================
.. index:: statement: continue
statement: for
statement: while
pair: loop; statement
keyword: finally
.. productionlist::
continue_stmt: "continue"
.. index::
statement: for
statement: while
pair: loop; statement
keyword: finally
:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
:keyword:`while` loop, but not nested in a function or class definition or
:keyword:`finally` statement within that loop. [#]_ It continues with the next
@ -594,7 +534,7 @@ The :keyword:`import` statement
Import statements are executed in two steps: (1) find a module, and initialize
it if necessary; (2) define a name or names in the local namespace (of the scope
where the :keyword:`import` statement occurs). The first form (without
where the :keyword:`import` statement occurs). The first form (without
:keyword:`from`) repeats these steps for each identifier in the list. The form
with :keyword:`from` performs step (1) once, and then performs step (2)
repeatedly.
@ -611,9 +551,9 @@ execute the module's body.
pair: module; name
pair: built-in; module
pair: user-defined; module
module: sys
pair: filename; extension
triple: module; search; path
module: sys
The system maintains a table of modules that have been or are being initialized,
indexed by module name. This table is accessible as ``sys.modules``. When a
@ -676,9 +616,6 @@ raise a :exc:`SyntaxError`.
.. index::
keyword: from
statement: from
.. index::
triple: hierarchical; module; names
single: packages
single: __init__.py
@ -692,8 +629,6 @@ bothered to spell this out right now; see the URL
http://www.python.org/doc/essays/packages.html for more details, also about how
the module search works from inside a package.]
.. %
.. index:: builtin: __import__
The built-in function :func:`__import__` is provided to support applications
@ -731,10 +666,12 @@ can appear before a future statement are:
* blank lines, and
* other future statements.
The features recognized by Python 2.5 are ``absolute_import``, ``division``,
``generators``, ``nested_scopes`` and ``with_statement``. ``generators`` and
``nested_scopes`` are redundant in Python version 2.3 and above because they
are always enabled.
.. XXX change this if future is cleaned out
The features recognized by Python 3.0 are ``absolute_import``, ``division``,
``generators``, ``nested_scopes`` and ``with_statement``. They are all
redundant because they are always enabled, and only kept for backwards
compatibility.
A future statement is recognized and treated specially at compile time: Changes
to the semantics of core constructs are often implemented by generating
@ -762,11 +699,10 @@ That is not a future statement; it's an ordinary import statement with no
special semantics or syntax restrictions.
Code compiled by calls to the builtin functions :func:`exec` and :func:`compile`
that occur in a module :mod:`M` containing a future
statement will, by default, use the new syntax or semantics associated with the
future statement. This can, starting with Python 2.2 be controlled by optional
arguments to :func:`compile` --- see the documentation of that function
for details.
that occur in a module :mod:`M` containing a future statement will, by default,
use the new syntax or semantics associated with the future statement. This can
be controlled by optional arguments to :func:`compile` --- see the documentation
of that function for details.
A future statement typed at an interactive interpreter prompt will take effect
for the rest of the interpreter session. If an interpreter is started with the
@ -817,6 +753,20 @@ block *containing* the function call, and code contained in such a string is
unaffected by :keyword:`global` statements in the code containing the function
call. The same applies to the :func:`eval` and :func:`compile` functions.
.. _nonlocal:
The :keyword:`nonlocal` statement
=================================
.. index:: statement: nonlocal
.. productionlist::
nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
XXX: To be documented.
.. rubric:: Footnotes
.. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The

View file

@ -53,9 +53,9 @@ a complete program; each statement is executed in the namespace of
Under Unix, a complete program can be passed to the interpreter in three forms:
with the :option:`-c` *string* command line option, as a file passed as the
first command line argument, or as standard input. If the file or standard input
is a tty device, the interpreter enters interactive mode; otherwise, it executes
the file as a complete program.
first command line argument, or as standard input. If the file or standard
input is a tty device, the interpreter enters interactive mode; otherwise, it
executes the file as a complete program.
.. _file-input: