Kaydet (Commit) a73a34d1 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

merge

...@@ -22,14 +22,14 @@ also syntactically compound statements. ...@@ -22,14 +22,14 @@ also syntactically compound statements.
single: clause single: clause
single: suite single: suite
Compound statements consist of one or more 'clauses.' A clause consists of a A compound statement consists of one or more 'clauses.' A clause consists of a
header and a 'suite.' The clause headers of a particular compound statement are header and a 'suite.' The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon. A suite is a group of statements identifying keyword and ends with a colon. A suite is a group of statements
controlled by a clause. A suite can be one or more semicolon-separated simple controlled by a clause. A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header's colon, or it 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 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, form of a suite can contain nested compound statements; the following is illegal,
mostly because it wouldn't be clear to which :keyword:`if` clause a following mostly because it wouldn't be clear to which :keyword:`if` clause a following
:keyword:`else` clause would belong:: :keyword:`else` clause would belong::
...@@ -156,8 +156,8 @@ The :keyword:`for` statement is used to iterate over the elements of a sequence ...@@ -156,8 +156,8 @@ The :keyword:`for` statement is used to iterate over the elements of a sequence
The expression list is evaluated once; it should yield an iterable object. An 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 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 then executed once for each item provided by the iterator, in the order returned
ascending indices. Each item in turn is assigned to the target list using the by the iterator. Each item in turn is assigned to the target list using the
standard rules for assignments (see :ref:`assignment`), and then the suite is standard rules for assignments (see :ref:`assignment`), and then the suite is
executed. When the items are exhausted (which is immediately when the sequence 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 is empty or an iterator raises a :exc:`StopIteration` exception), the suite in
...@@ -170,17 +170,25 @@ the :keyword:`else` clause, if present, is executed, and the loop terminates. ...@@ -170,17 +170,25 @@ the :keyword:`else` clause, if present, is executed, and the loop terminates.
A :keyword:`break` statement executed in the first suite terminates the loop A :keyword:`break` statement executed in the first suite terminates the loop
without executing the :keyword:`else` clause's suite. A :keyword:`continue` without executing the :keyword:`else` clause's suite. A :keyword:`continue`
statement executed in the first suite skips the rest of the suite and continues statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the :keyword:`else` clause if there was no next with the next item, or with the :keyword:`else` clause if there is no next
item. item.
The suite may assign to the variable(s) in the target list; this does not affect The for-loop makes assignments to the variables(s) in the target list.
the next item assigned to it. This overwrites all previous assignments to those variables including
those made in the suite of the for-loop::
for i in range(10):
print(i)
i = 5 # this will not affect the for-loop
# be i will be overwritten with the next
# index in the range
.. index:: .. index::
builtin: range builtin: range
Names in the target list are not deleted when the loop is finished, but if the 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: sequence is empty, they 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 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., ``list(range(3))`` emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))``
returns the list ``[0, 1, 2]``. returns the list ``[0, 1, 2]``.
...@@ -284,7 +292,7 @@ keeping all locals in that frame alive until the next garbage collection occurs. ...@@ -284,7 +292,7 @@ keeping all locals in that frame alive until the next garbage collection occurs.
object: traceback object: traceback
Before an except clause's suite is executed, details about the exception are 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`. stored in the :mod:`sys` module and can be accessed via :func:`sys.exc_info`.
:func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the :func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the
exception instance and a traceback object (see section :ref:`types`) identifying exception instance and a traceback object (see section :ref:`types`) identifying
the point in the program where the exception occurred. :func:`sys.exc_info` the point in the program where the exception occurred. :func:`sys.exc_info`
...@@ -461,7 +469,7 @@ A function definition defines a user-defined function object (see section ...@@ -461,7 +469,7 @@ A function definition defines a user-defined function object (see section
decorator: "@" `dotted_name` ["(" [`parameter_list` [","]] ")"] NEWLINE decorator: "@" `dotted_name` ["(" [`parameter_list` [","]] ")"] NEWLINE
dotted_name: `identifier` ("." `identifier`)* dotted_name: `identifier` ("." `identifier`)*
parameter_list: (`defparameter` ",")* parameter_list: (`defparameter` ",")*
: ( "*" [`parameter`] ("," `defparameter`)* ["," "**" `parameter`] : | "*" [`parameter`] ("," `defparameter`)* ["," "**" `parameter`]
: | "**" `parameter` : | "**" `parameter`
: | `defparameter` [","] ) : | `defparameter` [","] )
parameter: `identifier` [":" `expression`] parameter: `identifier` [":" `expression`]
......
...@@ -77,7 +77,7 @@ are still reachable. ...@@ -77,7 +77,7 @@ are still reachable.
module for information on controlling the collection of cyclic garbage. module for information on controlling the collection of cyclic garbage.
Other implementations act differently and CPython may change. Other implementations act differently and CPython may change.
Do not depend on immediate finalization of objects when they become Do not depend on immediate finalization of objects when they become
unreachable (ex: always close files). unreachable (so you should always close files explicitly).
Note that the use of the implementation's tracing or debugging facilities may Note that the use of the implementation's tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching keep objects alive that would normally be collectable. Also note that catching
...@@ -1722,7 +1722,7 @@ property creation, proxies, frameworks, and automatic resource ...@@ -1722,7 +1722,7 @@ property creation, proxies, frameworks, and automatic resource
locking/synchronization. locking/synchronization.
Here is an example of a metaclass that uses an :class:`collections.OrderedDict` Here is an example of a metaclass that uses an :class:`collections.OrderedDict`
to remember the order that class members were defined:: to remember the order that class variables are defined::
class OrderedClass(type): class OrderedClass(type):
......
...@@ -31,11 +31,11 @@ that name established in the innermost function block containing the use. ...@@ -31,11 +31,11 @@ that name established in the innermost function block containing the use.
A :dfn:`block` is a piece of Python program text that is executed as a unit. A :dfn:`block` is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition. The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block. A script file (a file given as Each command typed interactively is a block. A script file (a file given as
standard input to the interpreter or specified on the interpreter command line standard input to the interpreter or specified as a command line argument to the
the first argument) is a code block. A script command (a command specified on interpreter) is a code block. A script command (a command specified on the
the interpreter command line with the '**-c**' option) is a code block. The interpreter command line with the '**-c**' option) is a code block. The string
string argument passed to the built-in functions :func:`eval` and :func:`exec` argument passed to the built-in functions :func:`eval` and :func:`exec` is a
is a code block. code block.
.. index:: pair: execution; frame .. index:: pair: execution; frame
...@@ -77,7 +77,7 @@ global.) If a variable is used in a code block but not defined there, it is a ...@@ -77,7 +77,7 @@ global.) If a variable is used in a code block but not defined there, it is a
single: UnboundLocalError single: UnboundLocalError
When a name is not found at all, a :exc:`NameError` exception is raised. If the When a name is not found at all, a :exc:`NameError` exception is raised. If the
name refers to a local variable that has not been bound, a name refers to a local variable that has not been bound, an
:exc:`UnboundLocalError` exception is raised. :exc:`UnboundLocalError` is a :exc:`UnboundLocalError` exception is raised. :exc:`UnboundLocalError` is a
subclass of :exc:`NameError`. subclass of :exc:`NameError`.
......
This diff is collapsed.
...@@ -7,7 +7,7 @@ Simple statements ...@@ -7,7 +7,7 @@ Simple statements
.. index:: pair: simple; statement .. index:: pair: simple; statement
Simple statements are comprised within a single logical line. Several simple A simple statement is comprised within a single logical line. Several simple
statements may occur on a single line separated by semicolons. The syntax for statements may occur on a single line separated by semicolons. The syntax for
simple statements is: simple statements is:
...@@ -91,8 +91,8 @@ attributes or items of mutable objects: ...@@ -91,8 +91,8 @@ attributes or items of mutable objects:
: | `slicing` : | `slicing`
: | "*" `target` : | "*" `target`
(See section :ref:`primaries` for the syntax definitions for the last three (See section :ref:`primaries` for the syntax definitions for *attributeref*,
symbols.) *subscription*, and *slicing*.)
An assignment statement evaluates the expression list (remember that this can be 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 a single expression or a comma-separated list, the latter yielding a tuple) and
...@@ -228,7 +228,7 @@ Assignment of an object to a single target is recursively defined as follows. ...@@ -228,7 +228,7 @@ Assignment of an object to a single target is recursively defined as follows.
inclusive. Finally, the sequence object is asked to replace the slice with 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 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 from the length of the assigned sequence, thus changing the length of the
target sequence, if the object allows it. target sequence, if the target sequence allows it.
.. impl-detail:: .. impl-detail::
...@@ -236,14 +236,15 @@ Assignment of an object to a single target is recursively defined as follows. ...@@ -236,14 +236,15 @@ Assignment of an object to a single target is recursively defined as follows.
as for expressions, and invalid syntax is rejected during the code generation as for expressions, and invalid syntax is rejected during the code generation
phase, causing less detailed error messages. phase, causing less detailed error messages.
WARNING: Although the definition of assignment implies that overlaps between the Although the definition of assignment implies that overlaps between the
left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a`` left-hand side and the right-hand side are 'simultanenous' (for example ``a, b =
swaps two variables), overlaps *within* the collection of assigned-to variables b, a`` swaps two variables), overlaps *within* the collection of assigned-to
are not safe! For instance, the following program prints ``[0, 2]``:: variables occur left-to-right, sometimes resulting in confusion. For instance,
the following program prints ``[0, 2]``::
x = [0, 1] x = [0, 1]
i = 0 i = 0
i, x[i] = 1, 2 i, x[i] = 1, 2 # i is updated, then x[i] is updated
print(x) print(x)
...@@ -283,7 +284,7 @@ operation and an assignment statement: ...@@ -283,7 +284,7 @@ operation and an assignment statement:
augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**=" augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
: | ">>=" | "<<=" | "&=" | "^=" | "|=" : | ">>=" | "<<=" | "&=" | "^=" | "|="
(See section :ref:`primaries` for the syntax definitions for the last three (See section :ref:`primaries` for the syntax definitions of the last three
symbols.) symbols.)
An augmented assignment evaluates the target (which, unlike normal assignment An augmented assignment evaluates the target (which, unlike normal assignment
...@@ -297,6 +298,11 @@ version, ``x`` is only evaluated once. Also, when possible, the actual operation ...@@ -297,6 +298,11 @@ version, ``x`` is only evaluated once. Also, when possible, the actual operation
is performed *in-place*, meaning that rather than creating a new object and is performed *in-place*, meaning that rather than creating a new object and
assigning that to the target, the old object is modified instead. assigning that to the target, the old object is modified instead.
Unlike normal assignments, augmented assignments evaluate the left-hand side
*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
lastly, it writes the result back to ``a[i]``.
With the exception of assigning to tuples and multiple targets in a single With the exception of assigning to tuples and multiple targets in a single
statement, the assignment done by augmented assignment statements is handled the statement, the assignment done by augmented assignment statements is handled the
same way as normal assignments. Similarly, with the exception of the possible same way as normal assignments. Similarly, with the exception of the possible
...@@ -658,7 +664,7 @@ commas) the two steps are carried out separately for each clause, just ...@@ -658,7 +664,7 @@ commas) the two steps are carried out separately for each clause, just
as though the clauses had been separated out into individiual import as though the clauses had been separated out into individiual import
statements. statements.
The details of the first step, finding and loading modules is described in The details of the first step, finding and loading modules are described in
greater detail in the section on the :ref:`import system <importsystem>`, greater detail in the section on the :ref:`import system <importsystem>`,
which also describes the various types of packages and modules that can which also describes the various types of packages and modules that can
be imported, as well as all the hooks that can be used to customize be imported, as well as all the hooks that can be used to customize
...@@ -689,7 +695,7 @@ available in the local namespace in one of three ways: ...@@ -689,7 +695,7 @@ available in the local namespace in one of three ways:
The :keyword:`from` form uses a slightly more complex process: The :keyword:`from` form uses a slightly more complex process:
#. find the module specified in the :keyword:`from` clause loading and #. find the module specified in the :keyword:`from` clause, loading and
initializing it if necessary; initializing it if necessary;
#. for each of the identifiers specified in the :keyword:`import` clauses: #. for each of the identifiers specified in the :keyword:`import` clauses:
...@@ -697,7 +703,7 @@ The :keyword:`from` form uses a slightly more complex process: ...@@ -697,7 +703,7 @@ The :keyword:`from` form uses a slightly more complex process:
#. if not, attempt to import a submodule with that name and then #. if not, attempt to import a submodule with that name and then
check the imported module again for that attribute check the imported module again for that attribute
#. if the attribute is not found, :exc:`ImportError` is raised. #. if the attribute is not found, :exc:`ImportError` is raised.
#. otherwise, a reference to that value is bound in the local namespace, #. otherwise, a reference to that value is stored in the local namespace,
using the name in the :keyword:`as` clause if it is present, using the name in the :keyword:`as` clause if it is present,
otherwise using the attribute name otherwise using the attribute name
...@@ -726,9 +732,9 @@ to avoid accidentally exporting items that are not part of the API (such as ...@@ -726,9 +732,9 @@ to avoid accidentally exporting items that are not part of the API (such as
library modules which were imported and used within the module). library modules which were imported and used within the module).
The :keyword:`from` form with ``*`` may only occur in a module scope. The wild The :keyword:`from` form with ``*`` may only occur in a module scope. The wild
card form of import --- ``import *`` --- is only allowed at the module level. card form of import --- ``from module import *`` --- is only allowed at the
Attempting to use it in class or function definitions will raise a module level. Attempting to use it in class or function definitions will raise
:exc:`SyntaxError`. a :exc:`SyntaxError`.
.. index:: .. index::
single: relative; import single: relative; import
...@@ -747,7 +753,7 @@ import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``. ...@@ -747,7 +753,7 @@ import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
The specification for relative imports is contained within :pep:`328`. The specification for relative imports is contained within :pep:`328`.
:func:`importlib.import_module` is provided to support applications that :func:`importlib.import_module` is provided to support applications that
determine which modules need to be loaded dynamically. determine dynamically the modules to be loaded.
.. _future: .. _future:
...@@ -759,10 +765,12 @@ Future statements ...@@ -759,10 +765,12 @@ Future statements
A :dfn:`future statement` is a directive to the compiler that a particular A :dfn:`future statement` is a directive to the compiler that a particular
module should be compiled using syntax or semantics that will be available in a module should be compiled using syntax or semantics that will be available in a
specified future release of Python. The future statement is intended to ease specified future release of Python where the feature becomes standard.
migration to future versions of Python that introduce incompatible changes to
the language. It allows use of the new features on a per-module basis before The future statement is intended to ease migration to future versions of Python
the release in which the feature becomes standard. that introduce incompatible changes to the language. It allows use of the new
features on a per-module basis before the release in which the feature becomes
standard.
.. productionlist:: * .. productionlist:: *
future_statement: "from" "__future__" "import" feature ["as" name] future_statement: "from" "__future__" "import" feature ["as" name]
...@@ -857,7 +865,7 @@ definition, function definition, or :keyword:`import` statement. ...@@ -857,7 +865,7 @@ definition, function definition, or :keyword:`import` statement.
.. impl-detail:: .. impl-detail::
The current implementation does not enforce the latter two restrictions, but The current implementation does not enforce the two restrictions, but
programs should not abuse this freedom, as future implementations may enforce programs should not abuse this freedom, as future implementations may enforce
them or silently change the meaning of the program. them or silently change the meaning of the program.
...@@ -890,16 +898,16 @@ The :keyword:`nonlocal` statement ...@@ -890,16 +898,16 @@ The :keyword:`nonlocal` statement
: | "nonlocal" identifier augop expression_list : | "nonlocal" identifier augop expression_list
The :keyword:`nonlocal` statement causes the listed identifiers to refer to The :keyword:`nonlocal` statement causes the listed identifiers to refer to
previously bound variables in the nearest enclosing scope. This is important previously bound variables in the nearest enclosing scope excluding globals.
because the default behavior for binding is to search the local namespace This is important because the default behavior for binding is to search the
first. The statement allows encapsulated code to rebind variables outside of local namespace first. The statement allows encapsulated code to rebind
the local scope besides the global (module) scope. variables outside of the local scope besides the global (module) scope.
.. XXX not implemented .. XXX not implemented
The :keyword:`nonlocal` statement may prepend an assignment or augmented The :keyword:`nonlocal` statement may prepend an assignment or augmented
assignment, but not an expression. assignment, but not an expression.
Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
:keyword:`global` statement, must refer to pre-existing bindings in an :keyword:`global` statement, must refer to pre-existing bindings in an
enclosing scope (the scope in which a new binding should be created cannot enclosing scope (the scope in which a new binding should be created cannot
be determined unambiguously). be determined unambiguously).
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment