mirror of
https://github.com/python/cpython
synced 2024-09-05 00:05:39 +00:00
bpo-35506: Remove redundant and incorrect links from keywords. (GH-11174)
This commit is contained in:
parent
82d73554e4
commit
2b57c43f21
|
@ -738,7 +738,7 @@ Is it possible to write obfuscated one-liners in Python?
|
|||
--------------------------------------------------------
|
||||
|
||||
Yes. Usually this is done by nesting :keyword:`lambda` within
|
||||
:keyword:`lambda`. See the following three examples, due to Ulf Bartelt::
|
||||
:keyword:`!lambda`. See the following three examples, due to Ulf Bartelt::
|
||||
|
||||
from functools import reduce
|
||||
|
||||
|
|
|
@ -336,7 +336,7 @@ Glossary
|
|||
names, attribute access, operators or function calls which all return a
|
||||
value. In contrast to many other languages, not all language constructs
|
||||
are expressions. There are also :term:`statement`\s which cannot be used
|
||||
as expressions, such as :keyword:`if`. Assignments are also statements,
|
||||
as expressions, such as :keyword:`while`. Assignments are also statements,
|
||||
not expressions.
|
||||
|
||||
extension module
|
||||
|
@ -448,8 +448,8 @@ Glossary
|
|||
|
||||
generator expression
|
||||
An expression that returns an iterator. It looks like a normal expression
|
||||
followed by a :keyword:`for` expression defining a loop variable, range,
|
||||
and an optional :keyword:`if` expression. The combined expression
|
||||
followed by a :keyword:`!for` clause defining a loop variable, range,
|
||||
and an optional :keyword:`!if` clause. The combined expression
|
||||
generates values for an enclosing function::
|
||||
|
||||
>>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81
|
||||
|
|
|
@ -1108,7 +1108,7 @@ need to define a new function at all::
|
|||
existing_files = filter(os.path.exists, file_list)
|
||||
|
||||
If the function you need doesn't exist, you need to write it. One way to write
|
||||
small functions is to use the :keyword:`lambda` statement. ``lambda`` takes a
|
||||
small functions is to use the :keyword:`lambda` expression. ``lambda`` takes a
|
||||
number of parameters and an expression combining these parameters, and creates
|
||||
an anonymous function that returns the value of the expression::
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ Module :mod:`aifc` defines the following function:
|
|||
time how many samples you are going to write in total and use
|
||||
:meth:`writeframesraw` and :meth:`setnframes`.
|
||||
The :func:`.open` function may be used in a :keyword:`with` statement. When
|
||||
the :keyword:`with` block completes, the :meth:`~aifc.close` method is called.
|
||||
the :keyword:`!with` block completes, the :meth:`~aifc.close` method is called.
|
||||
|
||||
.. versionchanged:: 3.4
|
||||
Support for the :keyword:`with` statement was added.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
|
||||
========================================================================
|
||||
:mod:`!contextlib` --- Utilities for :keyword:`!with`\ -statement contexts
|
||||
==========================================================================
|
||||
|
||||
.. module:: contextlib
|
||||
:synopsis: Utilities for with-statement contexts.
|
||||
|
@ -72,7 +72,7 @@ Functions and classes provided:
|
|||
|
||||
The function being decorated must return a :term:`generator`-iterator when
|
||||
called. This iterator must yield exactly one value, which will be bound to
|
||||
the targets in the :keyword:`with` statement's :keyword:`as` clause, if any.
|
||||
the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any.
|
||||
|
||||
At the point where the generator yields, the block nested in the :keyword:`with`
|
||||
statement is executed. The generator is then resumed after the block is exited.
|
||||
|
@ -82,9 +82,9 @@ Functions and classes provided:
|
|||
the error (if any), or ensure that some cleanup takes place. If an exception is
|
||||
trapped merely in order to log it or to perform some action (rather than to
|
||||
suppress it entirely), the generator must reraise that exception. Otherwise the
|
||||
generator context manager will indicate to the :keyword:`with` statement that
|
||||
generator context manager will indicate to the :keyword:`!with` statement that
|
||||
the exception has been handled, and execution will resume with the statement
|
||||
immediately following the :keyword:`with` statement.
|
||||
immediately following the :keyword:`!with` statement.
|
||||
|
||||
:func:`contextmanager` uses :class:`ContextDecorator` so the context managers
|
||||
it creates can be used as decorators as well as in :keyword:`with` statements.
|
||||
|
@ -346,7 +346,7 @@ Functions and classes provided:
|
|||
As the decorated function must be able to be called multiple times, the
|
||||
underlying context manager must support use in multiple :keyword:`with`
|
||||
statements. If this is not the case, then the original construct with the
|
||||
explicit :keyword:`with` statement inside the function should be used.
|
||||
explicit :keyword:`!with` statement inside the function should be used.
|
||||
|
||||
.. versionadded:: 3.2
|
||||
|
||||
|
@ -771,7 +771,7 @@ Reentrant context managers
|
|||
|
||||
More sophisticated context managers may be "reentrant". These context
|
||||
managers can not only be used in multiple :keyword:`with` statements,
|
||||
but may also be used *inside* a :keyword:`with` statement that is already
|
||||
but may also be used *inside* a :keyword:`!with` statement that is already
|
||||
using the same context manager.
|
||||
|
||||
:class:`threading.RLock` is an example of a reentrant context manager, as are
|
||||
|
|
|
@ -63,7 +63,7 @@ The following function is the primary interface of this module:
|
|||
|
||||
The :class:`FileInput` instance can be used as a context manager in the
|
||||
:keyword:`with` statement. In this example, *input* is closed after the
|
||||
:keyword:`with` statement is exited, even if an exception occurs::
|
||||
:keyword:`!with` statement is exited, even if an exception occurs::
|
||||
|
||||
with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
|
||||
for line in f:
|
||||
|
@ -155,7 +155,7 @@ available for subclassing as well:
|
|||
|
||||
A :class:`FileInput` instance can be used as a context manager in the
|
||||
:keyword:`with` statement. In this example, *input* is closed after the
|
||||
:keyword:`with` statement is exited, even if an exception occurs::
|
||||
:keyword:`!with` statement is exited, even if an exception occurs::
|
||||
|
||||
with FileInput(files=('spam.txt', 'eggs.txt')) as input:
|
||||
process(input)
|
||||
|
|
|
@ -1665,7 +1665,7 @@ are always available. They are listed here in alphabetical order.
|
|||
This function is invoked by the :keyword:`import` statement. It can be
|
||||
replaced (by importing the :mod:`builtins` module and assigning to
|
||||
``builtins.__import__``) in order to change semantics of the
|
||||
:keyword:`import` statement, but doing so is **strongly** discouraged as it
|
||||
:keyword:`!import` statement, but doing so is **strongly** discouraged as it
|
||||
is usually simpler to use import hooks (see :pep:`302`) to attain the same
|
||||
goals and does not cause issues with code which assumes the default import
|
||||
implementation is in use. Direct use of :func:`__import__` is also
|
||||
|
|
|
@ -39,7 +39,7 @@ base class:
|
|||
|
||||
The :class:`IMAP4` class supports the :keyword:`with` statement. When used
|
||||
like this, the IMAP4 ``LOGOUT`` command is issued automatically when the
|
||||
:keyword:`with` statement exits. E.g.::
|
||||
:keyword:`!with` statement exits. E.g.::
|
||||
|
||||
>>> from imaplib import IMAP4
|
||||
>>> with IMAP4("domain.org") as M:
|
||||
|
|
|
@ -179,7 +179,7 @@ This module provides an interface to the mechanisms used to implement the
|
|||
If a module imports objects from another module using :keyword:`from` ...
|
||||
:keyword:`import` ..., calling :func:`reload` for the other module does not
|
||||
redefine the objects imported from it --- one way around this is to re-execute
|
||||
the :keyword:`from` statement, another is to use :keyword:`import` and qualified
|
||||
the :keyword:`!from` statement, another is to use :keyword:`!import` and qualified
|
||||
names (*module*.*name*) instead.
|
||||
|
||||
If a module instantiates instances of a class, reloading the module that defines
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
:mod:`importlib` --- The implementation of :keyword:`import`
|
||||
============================================================
|
||||
:mod:`!importlib` --- The implementation of :keyword:`!import`
|
||||
==============================================================
|
||||
|
||||
.. module:: importlib
|
||||
:synopsis: The implementation of the import machinery.
|
||||
|
@ -19,7 +19,7 @@ Introduction
|
|||
The purpose of the :mod:`importlib` package is two-fold. One is to provide the
|
||||
implementation of the :keyword:`import` statement (and thus, by extension, the
|
||||
:func:`__import__` function) in Python source code. This provides an
|
||||
implementation of :keyword:`import` which is portable to any Python
|
||||
implementation of :keyword:`!import` which is portable to any Python
|
||||
interpreter. This also provides an implementation which is easier to
|
||||
comprehend than one implemented in a programming language other than Python.
|
||||
|
||||
|
@ -197,7 +197,7 @@ Functions
|
|||
If a module imports objects from another module using :keyword:`from` ...
|
||||
:keyword:`import` ..., calling :func:`reload` for the other module does not
|
||||
redefine the objects imported from it --- one way around this is to
|
||||
re-execute the :keyword:`from` statement, another is to use :keyword:`import`
|
||||
re-execute the :keyword:`!from` statement, another is to use :keyword:`!import`
|
||||
and qualified names (*module.name*) instead.
|
||||
|
||||
If a module instantiates instances of a class, reloading the module that
|
||||
|
|
|
@ -249,7 +249,7 @@ I/O Base Classes
|
|||
|
||||
:class:`IOBase` is also a context manager and therefore supports the
|
||||
:keyword:`with` statement. In this example, *file* is closed after the
|
||||
:keyword:`with` statement's suite is finished---even if an exception occurs::
|
||||
:keyword:`!with` statement's suite is finished---even if an exception occurs::
|
||||
|
||||
with open('spam.txt', 'w') as file:
|
||||
file.write('Spam and eggs!')
|
||||
|
|
|
@ -63,7 +63,7 @@ of the production as recognized in the input string: these are always sequences
|
|||
which have the same form as the parent. An important aspect of this structure
|
||||
which should be noted is that keywords used to identify the parent node type,
|
||||
such as the keyword :keyword:`if` in an :const:`if_stmt`, are included in the
|
||||
node tree without any special treatment. For example, the :keyword:`if` keyword
|
||||
node tree without any special treatment. For example, the :keyword:`!if` keyword
|
||||
is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value
|
||||
associated with all :const:`NAME` tokens, including variable and function names
|
||||
defined by the user. In an alternate form returned when line number information
|
||||
|
|
|
@ -931,7 +931,7 @@ The following example reads the resulting pickled data. ::
|
|||
.. [#] Don't confuse this with the :mod:`marshal` module
|
||||
|
||||
.. [#] This is why :keyword:`lambda` functions cannot be pickled: all
|
||||
:keyword:`lambda` functions share the same name: ``<lambda>``.
|
||||
:keyword:`!lambda` functions share the same name: ``<lambda>``.
|
||||
|
||||
.. [#] The exception raised will likely be an :exc:`ImportError` or an
|
||||
:exc:`AttributeError` but it could be something else.
|
||||
|
|
|
@ -46,7 +46,7 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
|
|||
|
||||
The :class:`SMTP` class supports the :keyword:`with` statement. When used
|
||||
like this, the SMTP ``QUIT`` command is issued automatically when the
|
||||
:keyword:`with` statement exits. E.g.::
|
||||
:keyword:`!with` statement exits. E.g.::
|
||||
|
||||
>>> from smtplib import SMTP
|
||||
>>> with SMTP("domain.org") as smtp:
|
||||
|
|
|
@ -57,7 +57,7 @@ the server in a :keyword:`with` statement. Then call the
|
|||
:meth:`~BaseServer.handle_request` or
|
||||
:meth:`~BaseServer.serve_forever` method of the server object to
|
||||
process one or many requests. Finally, call :meth:`~BaseServer.server_close`
|
||||
to close the socket (unless you used a :keyword:`with` statement).
|
||||
to close the socket (unless you used a :keyword:`!with` statement).
|
||||
|
||||
When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
|
||||
you should explicitly declare how you want your threads to behave on an abrupt
|
||||
|
|
|
@ -74,8 +74,8 @@ one of their operands.)
|
|||
|
||||
.. _boolean:
|
||||
|
||||
Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
|
||||
====================================================================
|
||||
Boolean Operations --- :keyword:`!and`, :keyword:`!or`, :keyword:`!not`
|
||||
=======================================================================
|
||||
|
||||
.. index:: pair: Boolean; operations
|
||||
|
||||
|
@ -4460,7 +4460,7 @@ before the statement body is executed and exited when the statement ends:
|
|||
|
||||
Enter the runtime context and return either this object or another object
|
||||
related to the runtime context. The value returned by this method is bound to
|
||||
the identifier in the :keyword:`as` clause of :keyword:`with` statements using
|
||||
the identifier in the :keyword:`!as` clause of :keyword:`with` statements using
|
||||
this context manager.
|
||||
|
||||
An example of a context manager that returns itself is a :term:`file object`.
|
||||
|
@ -4472,7 +4472,7 @@ before the statement body is executed and exited when the statement ends:
|
|||
decimal context to a copy of the original decimal context and then return the
|
||||
copy. This allows changes to be made to the current decimal context in the body
|
||||
of the :keyword:`with` statement without affecting code outside the
|
||||
:keyword:`with` statement.
|
||||
:keyword:`!with` statement.
|
||||
|
||||
|
||||
.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
|
||||
|
@ -4484,10 +4484,10 @@ before the statement body is executed and exited when the statement ends:
|
|||
|
||||
Returning a true value from this method will cause the :keyword:`with` statement
|
||||
to suppress the exception and continue execution with the statement immediately
|
||||
following the :keyword:`with` statement. Otherwise the exception continues
|
||||
following the :keyword:`!with` statement. Otherwise the exception continues
|
||||
propagating after this method has finished executing. Exceptions that occur
|
||||
during execution of this method will replace any exception that occurred in the
|
||||
body of the :keyword:`with` statement.
|
||||
body of the :keyword:`!with` statement.
|
||||
|
||||
The exception passed in should never be reraised explicitly - instead, this
|
||||
method should return a false value to indicate that the method completed
|
||||
|
|
|
@ -44,7 +44,7 @@ Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).
|
|||
an empty string for other reasons. See the individual descriptions below.
|
||||
|
||||
A :class:`Telnet` object is a context manager and can be used in a
|
||||
:keyword:`with` statement. When the :keyword:`with` block ends, the
|
||||
:keyword:`with` statement. When the :keyword:`!with` block ends, the
|
||||
:meth:`close` method is called::
|
||||
|
||||
>>> from telnetlib import Telnet
|
||||
|
|
|
@ -124,7 +124,7 @@ The module defines the following user-callable items:
|
|||
|
||||
The directory name can be retrieved from the :attr:`name` attribute of the
|
||||
returned object. When the returned object is used as a context manager, the
|
||||
:attr:`name` will be assigned to the target of the :keyword:`as` clause in
|
||||
:attr:`name` will be assigned to the target of the :keyword:`!as` clause in
|
||||
the :keyword:`with` statement, if there is one.
|
||||
|
||||
The directory can be explicitly cleaned up by calling the
|
||||
|
|
|
@ -973,8 +973,8 @@ As an example, here is a simple way to synchronize a client and server thread::
|
|||
|
||||
.. _with-locks:
|
||||
|
||||
Using locks, conditions, and semaphores in the :keyword:`with` statement
|
||||
------------------------------------------------------------------------
|
||||
Using locks, conditions, and semaphores in the :keyword:`!with` statement
|
||||
-------------------------------------------------------------------------
|
||||
|
||||
All of the objects provided by this module that have :meth:`acquire` and
|
||||
:meth:`release` methods can be used as context managers for a :keyword:`with`
|
||||
|
|
|
@ -40,7 +40,7 @@ The :mod:`wave` module defines the following function and exception:
|
|||
the file object.
|
||||
|
||||
The :func:`.open` function may be used in a :keyword:`with` statement. When
|
||||
the :keyword:`with` block completes, the :meth:`Wave_read.close()
|
||||
the :keyword:`!with` block completes, the :meth:`Wave_read.close()
|
||||
<wave.Wave_read.close>` or :meth:`Wave_write.close()
|
||||
<wave.Wave_write.close()>` method is called.
|
||||
|
||||
|
|
|
@ -126,7 +126,7 @@ module documentation. This section lists the differences between the API and
|
|||
|
||||
You can avoid calling this method explicitly by using the :keyword:`with`
|
||||
statement. The following code will automatically unlink *dom* when the
|
||||
:keyword:`with` block is exited::
|
||||
:keyword:`!with` block is exited::
|
||||
|
||||
with xml.dom.minidom.parse(datasource) as dom:
|
||||
... # Work with dom.
|
||||
|
|
|
@ -181,7 +181,7 @@ ZipFile Objects
|
|||
|
||||
ZipFile is also a context manager and therefore supports the
|
||||
:keyword:`with` statement. In the example, *myzip* is closed after the
|
||||
:keyword:`with` statement's suite is finished---even if an exception occurs::
|
||||
:keyword:`!with` statement's suite is finished---even if an exception occurs::
|
||||
|
||||
with ZipFile('spam.zip', 'w') as myzip:
|
||||
myzip.write('eggs.txt')
|
||||
|
|
|
@ -78,11 +78,11 @@ on a separate line for clarity.
|
|||
.. _elif:
|
||||
.. _else:
|
||||
|
||||
The :keyword:`if` statement
|
||||
===========================
|
||||
The :keyword:`!if` statement
|
||||
============================
|
||||
|
||||
.. index::
|
||||
statement: if
|
||||
! statement: if
|
||||
keyword: elif
|
||||
keyword: else
|
||||
single: : (colon); compound statement
|
||||
|
@ -103,14 +103,13 @@ false, the suite of the :keyword:`else` clause, if present, is executed.
|
|||
|
||||
.. _while:
|
||||
|
||||
The :keyword:`while` statement
|
||||
==============================
|
||||
The :keyword:`!while` statement
|
||||
===============================
|
||||
|
||||
.. index::
|
||||
statement: while
|
||||
! statement: while
|
||||
keyword: else
|
||||
pair: loop; statement
|
||||
keyword: else
|
||||
single: : (colon); compound statement
|
||||
|
||||
The :keyword:`while` statement is used for repeated execution as long as an
|
||||
|
@ -122,7 +121,7 @@ expression is true:
|
|||
|
||||
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
|
||||
suite of the :keyword:`!else` clause, if present, is executed and the loop
|
||||
terminates.
|
||||
|
||||
.. index::
|
||||
|
@ -130,25 +129,22 @@ terminates.
|
|||
statement: continue
|
||||
|
||||
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 goes back
|
||||
to testing the expression.
|
||||
|
||||
|
||||
.. _for:
|
||||
|
||||
The :keyword:`for` statement
|
||||
============================
|
||||
The :keyword:`!for` statement
|
||||
=============================
|
||||
|
||||
.. index::
|
||||
statement: for
|
||||
! statement: for
|
||||
keyword: in
|
||||
keyword: else
|
||||
pair: target; list
|
||||
pair: loop; statement
|
||||
keyword: in
|
||||
keyword: else
|
||||
pair: target; list
|
||||
object: sequence
|
||||
single: : (colon); compound statement
|
||||
|
||||
|
@ -166,16 +162,16 @@ 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
|
||||
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.
|
||||
the :keyword:`!else` clause, if present, is executed, and the loop terminates.
|
||||
|
||||
.. index::
|
||||
statement: break
|
||||
statement: continue
|
||||
|
||||
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
|
||||
with the next item, or with the :keyword:`else` clause if there is no next
|
||||
with the next item, or with the :keyword:`!else` clause if there is no next
|
||||
item.
|
||||
|
||||
The for-loop makes assignments to the variables in the target list.
|
||||
|
@ -224,11 +220,11 @@ returns the list ``[0, 1, 2]``.
|
|||
.. _except:
|
||||
.. _finally:
|
||||
|
||||
The :keyword:`try` statement
|
||||
============================
|
||||
The :keyword:`!try` statement
|
||||
=============================
|
||||
|
||||
.. index::
|
||||
statement: try
|
||||
! statement: try
|
||||
keyword: except
|
||||
keyword: finally
|
||||
keyword: else
|
||||
|
@ -250,7 +246,7 @@ for a group of statements:
|
|||
|
||||
The :keyword:`except` clause(s) specify one or more exception handlers. When no
|
||||
exception occurs in the :keyword:`try` clause, no exception handler is executed.
|
||||
When an exception occurs in the :keyword:`try` suite, a search for an exception
|
||||
When an exception occurs in the :keyword:`!try` suite, a search for an exception
|
||||
handler is started. This search inspects the except clauses in turn until one
|
||||
is found that matches the exception. An expression-less except clause, if
|
||||
present, must be last; it matches any exception. For an except clause with an
|
||||
|
@ -270,7 +266,7 @@ as if the entire :keyword:`try` statement raised the exception).
|
|||
.. index:: single: as; except clause
|
||||
|
||||
When a matching except clause is found, the exception is assigned to the target
|
||||
specified after the :keyword:`as` keyword in that except clause, if present, and
|
||||
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
|
||||
|
@ -314,22 +310,22 @@ from a function that handled an exception.
|
|||
statement: break
|
||||
statement: continue
|
||||
|
||||
The optional :keyword:`else` clause is executed if the control flow leaves the
|
||||
The optional :keyword:`!else` clause is executed if the control flow leaves the
|
||||
:keyword:`try` suite, no exception was raised, and no :keyword:`return`,
|
||||
:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in
|
||||
the :keyword:`else` clause are not handled by the preceding :keyword:`except`
|
||||
the :keyword:`!else` clause are not handled by the preceding :keyword:`except`
|
||||
clauses.
|
||||
|
||||
.. index:: keyword: finally
|
||||
|
||||
If :keyword:`finally` is present, it specifies a 'cleanup' handler. The
|
||||
:keyword:`try` clause is executed, including any :keyword:`except` and
|
||||
:keyword:`else` clauses. If an exception occurs in any of the clauses and is
|
||||
not handled, the exception is temporarily saved. The :keyword:`finally` clause
|
||||
:keyword:`!else` clauses. If an exception occurs in any of the clauses and is
|
||||
not handled, the exception is temporarily saved. The :keyword:`!finally` clause
|
||||
is executed. If there is a saved exception it is re-raised at the end of the
|
||||
:keyword:`finally` clause. If the :keyword:`finally` clause raises another
|
||||
:keyword:`!finally` clause. If the :keyword:`!finally` clause raises another
|
||||
exception, the saved exception is set as the context of the new exception.
|
||||
If the :keyword:`finally` clause executes a :keyword:`return`, :keyword:`break`
|
||||
If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break`
|
||||
or :keyword:`continue` statement, the saved exception is discarded::
|
||||
|
||||
>>> def f():
|
||||
|
@ -350,12 +346,12 @@ the :keyword:`finally` clause.
|
|||
statement: continue
|
||||
|
||||
When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is
|
||||
executed in the :keyword:`try` suite of a :keyword:`try`...\ :keyword:`finally`
|
||||
executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally`
|
||||
statement, the :keyword:`finally` clause is also executed 'on the way out.'
|
||||
|
||||
The return value of a function is determined by the last :keyword:`return`
|
||||
statement executed. Since the :keyword:`finally` clause always executes, a
|
||||
:keyword:`return` statement executed in the :keyword:`finally` clause will
|
||||
:keyword:`!return` statement executed in the :keyword:`!finally` clause will
|
||||
always be the last one executed::
|
||||
|
||||
>>> def foo():
|
||||
|
@ -379,11 +375,11 @@ may be found in section :ref:`raise`.
|
|||
.. _with:
|
||||
.. _as:
|
||||
|
||||
The :keyword:`with` statement
|
||||
=============================
|
||||
The :keyword:`!with` statement
|
||||
==============================
|
||||
|
||||
.. index::
|
||||
statement: with
|
||||
! statement: with
|
||||
keyword: as
|
||||
single: as; with statement
|
||||
single: , (comma); with statement
|
||||
|
@ -595,7 +591,7 @@ name), for immediate use in expressions. This uses lambda expressions, describe
|
|||
section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a
|
||||
simplified function definition; a function defined in a ":keyword:`def`"
|
||||
statement can be passed around or assigned to another name just like a function
|
||||
defined by a lambda expression. The ":keyword:`def`" form is actually more powerful
|
||||
defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful
|
||||
since it allows the execution of multiple statements and annotations.
|
||||
|
||||
**Programmer's note:** Functions are first-class objects. A "``def``" statement
|
||||
|
@ -758,8 +754,8 @@ An example of a coroutine function::
|
|||
.. index:: statement: async for
|
||||
.. _`async for`:
|
||||
|
||||
The :keyword:`async for` statement
|
||||
----------------------------------
|
||||
The :keyword:`!async for` statement
|
||||
-----------------------------------
|
||||
|
||||
.. productionlist::
|
||||
async_for_stmt: "async" `for_stmt`
|
||||
|
@ -802,8 +798,8 @@ body of a coroutine function.
|
|||
.. index:: statement: async with
|
||||
.. _`async with`:
|
||||
|
||||
The :keyword:`async with` statement
|
||||
-----------------------------------
|
||||
The :keyword:`!async with` statement
|
||||
------------------------------------
|
||||
|
||||
.. productionlist::
|
||||
async_with_stmt: "async" `with_stmt`
|
||||
|
|
|
@ -620,7 +620,7 @@ Callable types
|
|||
called, always returns an iterator object which can be used to execute the
|
||||
body of the function: calling the iterator's :meth:`iterator.__next__`
|
||||
method will cause the function to execute until it provides a value
|
||||
using the :keyword:`yield` statement. When the function executes a
|
||||
using the :keyword:`!yield` statement. When the function executes a
|
||||
:keyword:`return` statement or falls off the end, a :exc:`StopIteration`
|
||||
exception is raised and the iterator will have reached the end of the set of
|
||||
values to be returned.
|
||||
|
@ -700,7 +700,7 @@ Modules
|
|||
|
||||
Modules are a basic organizational unit of Python code, and are created by
|
||||
the :ref:`import system <importsystem>` as invoked either by the
|
||||
:keyword:`import` statement (see :keyword:`import`), or by calling
|
||||
:keyword:`import` statement, or by calling
|
||||
functions such as :func:`importlib.import_module` and built-in
|
||||
:func:`__import__`. A module object has a namespace implemented by a
|
||||
dictionary object (this is the dictionary referenced by the ``__globals__``
|
||||
|
@ -2423,7 +2423,7 @@ A :dfn:`context manager` is an object that defines the runtime context to be
|
|||
established when executing a :keyword:`with` statement. The context manager
|
||||
handles the entry into, and the exit from, the desired runtime context for the
|
||||
execution of the block of code. Context managers are normally invoked using the
|
||||
:keyword:`with` statement (described in section :ref:`with`), but can also be
|
||||
:keyword:`!with` statement (described in section :ref:`with`), but can also be
|
||||
used by directly invoking their methods.
|
||||
|
||||
.. index::
|
||||
|
@ -2440,7 +2440,7 @@ For more information on context managers, see :ref:`typecontextmanager`.
|
|||
|
||||
Enter the runtime context related to this object. The :keyword:`with` statement
|
||||
will bind this method's return value to the target(s) specified in the
|
||||
:keyword:`as` clause of the statement, if any.
|
||||
:keyword:`!as` clause of the statement, if any.
|
||||
|
||||
|
||||
.. method:: object.__exit__(self, exc_type, exc_value, traceback)
|
||||
|
|
|
@ -58,8 +58,8 @@ The following constructs bind names: formal parameters to functions,
|
|||
:keyword:`import` statements, class and function definitions (these bind the
|
||||
class or function name in the defining block), and targets that are identifiers
|
||||
if occurring in an assignment, :keyword:`for` loop header, or after
|
||||
:keyword:`as` in a :keyword:`with` statement or :keyword:`except` clause.
|
||||
The :keyword:`import` statement
|
||||
:keyword:`!as` in a :keyword:`with` statement or :keyword:`except` clause.
|
||||
The :keyword:`!import` statement
|
||||
of the form ``from ... import *`` binds all names defined in the imported
|
||||
module, except those beginning with an underscore. This form may only be used
|
||||
at the module level.
|
||||
|
@ -123,7 +123,7 @@ namespace. Names are resolved in the top-level namespace by searching the
|
|||
global namespace, i.e. the namespace of the module containing the code block,
|
||||
and the builtins namespace, the namespace of the module :mod:`builtins`. The
|
||||
global namespace is searched first. If the name is not found there, the
|
||||
builtins namespace is searched. The :keyword:`global` statement must precede
|
||||
builtins namespace is searched. The :keyword:`!global` statement must precede
|
||||
all uses of the name.
|
||||
|
||||
The :keyword:`global` statement has the same scope as a name binding operation
|
||||
|
|
|
@ -185,20 +185,20 @@ Common syntax elements for comprehensions are:
|
|||
comp_if: "if" `expression_nocond` [`comp_iter`]
|
||||
|
||||
The comprehension consists of a single expression followed by at least one
|
||||
:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
|
||||
:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses.
|
||||
In this case, the elements of the new container are those that would be produced
|
||||
by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
|
||||
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.
|
||||
|
||||
However, aside from the iterable expression in the leftmost :keyword:`for` clause,
|
||||
However, aside from the iterable expression in the leftmost :keyword:`!for` clause,
|
||||
the comprehension is executed in a separate implicitly nested scope. This ensures
|
||||
that names assigned to in the target list don't "leak" into the enclosing scope.
|
||||
|
||||
The iterable expression in the leftmost :keyword:`for` clause is evaluated
|
||||
The iterable expression in the leftmost :keyword:`!for` clause is evaluated
|
||||
directly in the enclosing scope and then passed as an argument to the implictly
|
||||
nested scope. Subsequent :keyword:`for` clauses and any filter condition in the
|
||||
leftmost :keyword:`for` clause cannot be evaluated in the enclosing scope as
|
||||
nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the
|
||||
leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
|
||||
they may depend on the values obtained from the leftmost iterable. For example:
|
||||
``[x*y for x in range(10) for y in range(x, x+10)]``.
|
||||
|
||||
|
@ -209,14 +209,14 @@ nested scope.
|
|||
.. index::
|
||||
single: await; in comprehensions
|
||||
|
||||
Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
|
||||
Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
|
||||
clause may be used to iterate over a :term:`asynchronous iterator`.
|
||||
A comprehension in an :keyword:`async def` function may consist of either a
|
||||
:keyword:`for` or :keyword:`async for` clause following the leading
|
||||
expression, may contain additional :keyword:`for` or :keyword:`async for`
|
||||
A comprehension in an :keyword:`!async def` function may consist of either a
|
||||
:keyword:`!for` or :keyword:`!async for` clause following the leading
|
||||
expression, may contain additional :keyword:`!for` or :keyword:`!async for`
|
||||
clauses, and may also use :keyword:`await` expressions.
|
||||
If a comprehension contains either :keyword:`async for` clauses
|
||||
or :keyword:`await` expressions it is called an
|
||||
If a comprehension contains either :keyword:`!async for` clauses
|
||||
or :keyword:`!await` expressions it is called an
|
||||
:dfn:`asynchronous comprehension`. An asynchronous comprehension may
|
||||
suspend the execution of the coroutine function in which it appears.
|
||||
See also :pep:`530`.
|
||||
|
@ -360,11 +360,11 @@ brackets or curly braces.
|
|||
Variables used in the generator expression are evaluated lazily when the
|
||||
:meth:`~generator.__next__` method is called for the generator object (in the same
|
||||
fashion as normal generators). However, the iterable expression in the
|
||||
leftmost :keyword:`for` clause is immediately evaluated, so that an error
|
||||
leftmost :keyword:`!for` clause is immediately evaluated, so that an error
|
||||
produced by it will be emitted at the point where the generator expression
|
||||
is defined, rather than at the point where the first value is retrieved.
|
||||
Subsequent :keyword:`for` clauses and any filter condition in the leftmost
|
||||
:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
|
||||
Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
|
||||
:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
|
||||
depend on the values obtained from the leftmost iterable. For example:
|
||||
``(x*y for x in range(10) for y in range(x, x+10))``.
|
||||
|
||||
|
@ -375,7 +375,7 @@ To avoid interfering with the expected operation of the generator expression
|
|||
itself, ``yield`` and ``yield from`` expressions are prohibited in the
|
||||
implicitly defined generator.
|
||||
|
||||
If a generator expression contains either :keyword:`async for`
|
||||
If a generator expression contains either :keyword:`!async for`
|
||||
clauses or :keyword:`await` expressions it is called an
|
||||
:dfn:`asynchronous generator expression`. An asynchronous generator
|
||||
expression returns a new asynchronous generator object,
|
||||
|
@ -637,12 +637,12 @@ that method.
|
|||
In an asynchronous generator function, yield expressions are allowed anywhere
|
||||
in a :keyword:`try` construct. However, if an asynchronous generator is not
|
||||
resumed before it is finalized (by reaching a zero reference count or by
|
||||
being garbage collected), then a yield expression within a :keyword:`try`
|
||||
being garbage collected), then a yield expression within a :keyword:`!try`
|
||||
construct could result in a failure to execute pending :keyword:`finally`
|
||||
clauses. In this case, it is the responsibility of the event loop or
|
||||
scheduler running the asynchronous generator to call the asynchronous
|
||||
generator-iterator's :meth:`~agen.aclose` method and run the resulting
|
||||
coroutine object, thus allowing any pending :keyword:`finally` clauses
|
||||
coroutine object, thus allowing any pending :keyword:`!finally` clauses
|
||||
to execute.
|
||||
|
||||
To take care of finalization, an event loop should define
|
||||
|
@ -1548,7 +1548,7 @@ Membership test operations
|
|||
The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
|
||||
s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
|
||||
``x not in s`` returns the negation of ``x in s``. All built-in sequences and
|
||||
set types support this as well as dictionary, for which :keyword:`in` tests
|
||||
set types support this as well as dictionary, for which :keyword:`!in` tests
|
||||
whether the dictionary has a given key. For container types such as list, tuple,
|
||||
set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
|
||||
to ``any(x is e or x == e for e in y)``.
|
||||
|
@ -1648,6 +1648,8 @@ returns a boolean value regardless of the type of its argument
|
|||
(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
|
||||
|
||||
|
||||
.. _if_expr:
|
||||
|
||||
Conditional expressions
|
||||
=======================
|
||||
|
||||
|
@ -1790,7 +1792,7 @@ precedence and have a left-to-right chaining feature as described in the
|
|||
+===============================================+=====================================+
|
||||
| :keyword:`lambda` | Lambda expression |
|
||||
+-----------------------------------------------+-------------------------------------+
|
||||
| :keyword:`if` -- :keyword:`else` | Conditional expression |
|
||||
| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
|
||||
+-----------------------------------------------+-------------------------------------+
|
||||
| :keyword:`or` | Boolean OR |
|
||||
+-----------------------------------------------+-------------------------------------+
|
||||
|
|
|
@ -15,11 +15,11 @@ way. Functions such as :func:`importlib.import_module` and built-in
|
|||
|
||||
The :keyword:`import` statement combines two operations; it searches for the
|
||||
named module, then it binds the results of that search to a name in the local
|
||||
scope. The search operation of the :keyword:`import` statement is defined as
|
||||
scope. The search operation of the :keyword:`!import` statement is defined as
|
||||
a call to the :func:`__import__` function, with the appropriate arguments.
|
||||
The return value of :func:`__import__` is used to perform the name
|
||||
binding operation of the :keyword:`import` statement. See the
|
||||
:keyword:`import` statement for the exact details of that name binding
|
||||
binding operation of the :keyword:`!import` statement. See the
|
||||
:keyword:`!import` statement for the exact details of that name binding
|
||||
operation.
|
||||
|
||||
A direct call to :func:`__import__` performs only the module search and, if
|
||||
|
|
|
@ -369,11 +369,11 @@ target, then the interpreter evaluates the target except for the last
|
|||
|
||||
.. _assert:
|
||||
|
||||
The :keyword:`assert` statement
|
||||
===============================
|
||||
The :keyword:`!assert` statement
|
||||
================================
|
||||
|
||||
.. index::
|
||||
statement: assert
|
||||
! statement: assert
|
||||
pair: debugging; assertions
|
||||
single: , (comma); expression list
|
||||
|
||||
|
@ -412,8 +412,8 @@ is determined when the interpreter starts.
|
|||
|
||||
.. _pass:
|
||||
|
||||
The :keyword:`pass` statement
|
||||
=============================
|
||||
The :keyword:`!pass` statement
|
||||
==============================
|
||||
|
||||
.. index::
|
||||
statement: pass
|
||||
|
@ -434,11 +434,11 @@ code needs to be executed, for example::
|
|||
|
||||
.. _del:
|
||||
|
||||
The :keyword:`del` statement
|
||||
============================
|
||||
The :keyword:`!del` statement
|
||||
=============================
|
||||
|
||||
.. index::
|
||||
statement: del
|
||||
! statement: del
|
||||
pair: deletion; target
|
||||
triple: deletion; target; list
|
||||
|
||||
|
@ -473,11 +473,11 @@ the sliced object).
|
|||
|
||||
.. _return:
|
||||
|
||||
The :keyword:`return` statement
|
||||
===============================
|
||||
The :keyword:`!return` statement
|
||||
================================
|
||||
|
||||
.. index::
|
||||
statement: return
|
||||
! statement: return
|
||||
pair: function; definition
|
||||
pair: class; definition
|
||||
|
||||
|
@ -495,7 +495,7 @@ If an expression list is present, it is evaluated, else ``None`` is substituted.
|
|||
.. index:: keyword: finally
|
||||
|
||||
When :keyword:`return` passes control out of a :keyword:`try` statement with a
|
||||
:keyword:`finally` clause, that :keyword:`finally` clause is executed before
|
||||
:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
|
||||
really leaving the function.
|
||||
|
||||
In a generator function, the :keyword:`return` statement indicates that the
|
||||
|
@ -505,13 +505,13 @@ becomes the :attr:`StopIteration.value` attribute.
|
|||
|
||||
In an asynchronous generator function, an empty :keyword:`return` statement
|
||||
indicates that the asynchronous generator is done and will cause
|
||||
:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`return`
|
||||
:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return`
|
||||
statement is a syntax error in an asynchronous generator function.
|
||||
|
||||
.. _yield:
|
||||
|
||||
The :keyword:`yield` statement
|
||||
==============================
|
||||
The :keyword:`!yield` statement
|
||||
===============================
|
||||
|
||||
.. index::
|
||||
statement: yield
|
||||
|
@ -546,11 +546,11 @@ For full details of :keyword:`yield` semantics, refer to the
|
|||
|
||||
.. _raise:
|
||||
|
||||
The :keyword:`raise` statement
|
||||
==============================
|
||||
The :keyword:`!raise` statement
|
||||
===============================
|
||||
|
||||
.. index::
|
||||
statement: raise
|
||||
! statement: raise
|
||||
single: exception
|
||||
pair: raising; exception
|
||||
single: __traceback__ (exception attribute)
|
||||
|
@ -649,11 +649,11 @@ and information about handling exceptions is in section :ref:`try`.
|
|||
|
||||
.. _break:
|
||||
|
||||
The :keyword:`break` statement
|
||||
==============================
|
||||
The :keyword:`!break` statement
|
||||
===============================
|
||||
|
||||
.. index::
|
||||
statement: break
|
||||
! statement: break
|
||||
statement: for
|
||||
statement: while
|
||||
pair: loop; statement
|
||||
|
@ -668,7 +668,7 @@ that loop.
|
|||
.. index:: keyword: else
|
||||
pair: loop control; target
|
||||
|
||||
It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
|
||||
It terminates the nearest enclosing loop, skipping the optional :keyword:`!else`
|
||||
clause if the loop has one.
|
||||
|
||||
If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
|
||||
|
@ -677,17 +677,17 @@ target keeps its current value.
|
|||
.. index:: keyword: finally
|
||||
|
||||
When :keyword:`break` passes control out of a :keyword:`try` statement with a
|
||||
:keyword:`finally` clause, that :keyword:`finally` clause is executed before
|
||||
:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
|
||||
really leaving the loop.
|
||||
|
||||
|
||||
.. _continue:
|
||||
|
||||
The :keyword:`continue` statement
|
||||
=================================
|
||||
The :keyword:`!continue` statement
|
||||
==================================
|
||||
|
||||
.. index::
|
||||
statement: continue
|
||||
! statement: continue
|
||||
statement: for
|
||||
statement: while
|
||||
pair: loop; statement
|
||||
|
@ -701,18 +701,18 @@ The :keyword:`continue` statement
|
|||
that loop. It continues with the next cycle of the nearest enclosing loop.
|
||||
|
||||
When :keyword:`continue` passes control out of a :keyword:`try` statement with a
|
||||
:keyword:`finally` clause, that :keyword:`finally` clause is executed before
|
||||
:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
|
||||
really starting the next loop cycle.
|
||||
|
||||
|
||||
.. _import:
|
||||
.. _from:
|
||||
|
||||
The :keyword:`import` statement
|
||||
===============================
|
||||
The :keyword:`!import` statement
|
||||
================================
|
||||
|
||||
.. index::
|
||||
statement: import
|
||||
! statement: import
|
||||
single: module; importing
|
||||
pair: name; binding
|
||||
keyword: from
|
||||
|
@ -755,8 +755,8 @@ available in the local namespace in one of three ways:
|
|||
|
||||
.. index:: single: as; import statement
|
||||
|
||||
* If the module name is followed by :keyword:`as`, then the name
|
||||
following :keyword:`as` is bound directly to the imported module.
|
||||
* If the module name is followed by :keyword:`!as`, then the name
|
||||
following :keyword:`!as` is bound directly to the imported module.
|
||||
* If no other name is specified, and the module being imported is a top
|
||||
level module, the module's name is bound in the local namespace as a
|
||||
reference to the imported module
|
||||
|
@ -781,7 +781,7 @@ The :keyword:`from` form uses a slightly more complex process:
|
|||
check the imported module again for that attribute
|
||||
#. if the attribute is not found, :exc:`ImportError` is raised.
|
||||
#. 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
|
||||
|
||||
Examples::
|
||||
|
@ -922,11 +922,11 @@ after the script is executed.
|
|||
|
||||
.. _global:
|
||||
|
||||
The :keyword:`global` statement
|
||||
===============================
|
||||
The :keyword:`!global` statement
|
||||
================================
|
||||
|
||||
.. index::
|
||||
statement: global
|
||||
! statement: global
|
||||
triple: global; name; binding
|
||||
single: , (comma); identifier list
|
||||
|
||||
|
@ -936,11 +936,11 @@ The :keyword:`global` statement
|
|||
The :keyword:`global` statement is a declaration which holds for the entire
|
||||
current code block. It means that the listed identifiers are to be interpreted
|
||||
as globals. It would be impossible to assign to a global variable without
|
||||
:keyword:`global`, although free variables may refer to globals without being
|
||||
:keyword:`!global`, although free variables may refer to globals without being
|
||||
declared global.
|
||||
|
||||
Names listed in a :keyword:`global` statement must not be used in the same code
|
||||
block textually preceding that :keyword:`global` statement.
|
||||
block textually preceding that :keyword:`!global` statement.
|
||||
|
||||
Names listed in a :keyword:`global` statement must not be defined as formal
|
||||
parameters or in a :keyword:`for` loop control target, :keyword:`class`
|
||||
|
@ -959,18 +959,18 @@ annotation.
|
|||
builtin: compile
|
||||
|
||||
**Programmer's note:** :keyword:`global` is a directive to the parser. It
|
||||
applies only to code parsed at the same time as the :keyword:`global` statement.
|
||||
In particular, a :keyword:`global` statement contained in a string or code
|
||||
applies only to code parsed at the same time as the :keyword:`!global` statement.
|
||||
In particular, a :keyword:`!global` statement contained in a string or code
|
||||
object supplied to the built-in :func:`exec` function does not affect the code
|
||||
block *containing* the function call, and code contained in such a string is
|
||||
unaffected by :keyword:`global` statements in the code containing the function
|
||||
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
|
||||
=================================
|
||||
The :keyword:`!nonlocal` statement
|
||||
==================================
|
||||
|
||||
.. index:: statement: nonlocal
|
||||
single: , (comma); identifier list
|
||||
|
|
|
@ -783,7 +783,7 @@ calls :func:`iter` on the container object. The function returns an iterator
|
|||
object that defines the method :meth:`~iterator.__next__` which accesses
|
||||
elements in the container one at a time. When there are no more elements,
|
||||
:meth:`~iterator.__next__` raises a :exc:`StopIteration` exception which tells the
|
||||
:keyword:`for` loop to terminate. You can call the :meth:`~iterator.__next__` method
|
||||
:keyword:`!for` loop to terminate. You can call the :meth:`~iterator.__next__` method
|
||||
using the :func:`next` built-in function; this example shows how it all works::
|
||||
|
||||
>>> s = 'abc'
|
||||
|
|
|
@ -10,8 +10,8 @@ control flow statements known from other languages, with some twists.
|
|||
|
||||
.. _tut-if:
|
||||
|
||||
:keyword:`if` Statements
|
||||
========================
|
||||
:keyword:`!if` Statements
|
||||
=========================
|
||||
|
||||
Perhaps the most well-known statement type is the :keyword:`if` statement. For
|
||||
example::
|
||||
|
@ -31,16 +31,16 @@ example::
|
|||
More
|
||||
|
||||
There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
|
||||
optional. The keyword ':keyword:`elif`' is short for 'else if', and is useful
|
||||
to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
|
||||
:keyword:`elif` ... sequence is a substitute for the ``switch`` or
|
||||
optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful
|
||||
to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ...
|
||||
:keyword:`!elif` ... sequence is a substitute for the ``switch`` or
|
||||
``case`` statements found in other languages.
|
||||
|
||||
|
||||
.. _tut-for:
|
||||
|
||||
:keyword:`for` Statements
|
||||
=========================
|
||||
:keyword:`!for` Statements
|
||||
==========================
|
||||
|
||||
.. index::
|
||||
statement: for
|
||||
|
@ -48,7 +48,7 @@ to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
|
|||
The :keyword:`for` statement in Python differs a bit from what you may be used
|
||||
to in C or Pascal. Rather than always iterating over an arithmetic progression
|
||||
of numbers (like in Pascal), or giving the user the ability to define both the
|
||||
iteration step and halting condition (as C), Python's :keyword:`for` statement
|
||||
iteration step and halting condition (as C), Python's :keyword:`!for` statement
|
||||
iterates over the items of any sequence (a list or a string), in the order that
|
||||
they appear in the sequence. For example (no pun intended):
|
||||
|
||||
|
@ -154,13 +154,13 @@ Later we will see more functions that return iterables and take iterables as arg
|
|||
|
||||
.. _tut-break:
|
||||
|
||||
:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
|
||||
=========================================================================================
|
||||
:keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops
|
||||
============================================================================================
|
||||
|
||||
The :keyword:`break` statement, like in C, breaks out of the innermost enclosing
|
||||
:keyword:`for` or :keyword:`while` loop.
|
||||
|
||||
Loop statements may have an ``else`` clause; it is executed when the loop
|
||||
Loop statements may have an :keyword:`!else` clause; it is executed when the loop
|
||||
terminates through exhaustion of the list (with :keyword:`for`) or when the
|
||||
condition becomes false (with :keyword:`while`), but not when the loop is
|
||||
terminated by a :keyword:`break` statement. This is exemplified by the
|
||||
|
@ -189,9 +189,9 @@ the :keyword:`for` loop, **not** the :keyword:`if` statement.)
|
|||
|
||||
When used with a loop, the ``else`` clause has more in common with the
|
||||
``else`` clause of a :keyword:`try` statement than it does that of
|
||||
:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs
|
||||
:keyword:`if` statements: a :keyword:`!try` statement's ``else`` clause runs
|
||||
when no exception occurs, and a loop's ``else`` clause runs when no ``break``
|
||||
occurs. For more on the :keyword:`try` statement and exceptions, see
|
||||
occurs. For more on the :keyword:`!try` statement and exceptions, see
|
||||
:ref:`tut-handling`.
|
||||
|
||||
The :keyword:`continue` statement, also borrowed from C, continues with the next
|
||||
|
@ -213,8 +213,8 @@ iteration of the loop::
|
|||
|
||||
.. _tut-pass:
|
||||
|
||||
:keyword:`pass` Statements
|
||||
==========================
|
||||
:keyword:`!pass` Statements
|
||||
===========================
|
||||
|
||||
The :keyword:`pass` statement does nothing. It can be used when a statement is
|
||||
required syntactically but the program requires no action. For example::
|
||||
|
@ -231,7 +231,7 @@ This is commonly used for creating minimal classes::
|
|||
|
||||
Another place :keyword:`pass` can be used is as a place-holder for a function or
|
||||
conditional body when you are working on new code, allowing you to keep thinking
|
||||
at a more abstract level. The :keyword:`pass` is silently ignored::
|
||||
at a more abstract level. The :keyword:`!pass` is silently ignored::
|
||||
|
||||
>>> def initlog(*args):
|
||||
... pass # Remember to implement this!
|
||||
|
@ -331,7 +331,7 @@ Fibonacci series, instead of printing it::
|
|||
This example, as usual, demonstrates some new Python features:
|
||||
|
||||
* The :keyword:`return` statement returns with a value from a function.
|
||||
:keyword:`return` without an expression argument returns ``None``. Falling off
|
||||
:keyword:`!return` without an expression argument returns ``None``. Falling off
|
||||
the end of a function also returns ``None``.
|
||||
|
||||
* The statement ``result.append(a)`` calls a *method* of the list object
|
||||
|
|
|
@ -216,9 +216,9 @@ or, equivalently::
|
|||
which is more concise and readable.
|
||||
|
||||
A list comprehension consists of brackets containing an expression followed
|
||||
by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
|
||||
by a :keyword:`!for` clause, then zero or more :keyword:`!for` or :keyword:`!if`
|
||||
clauses. The result will be a new list resulting from evaluating the expression
|
||||
in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
|
||||
in the context of the :keyword:`!for` and :keyword:`!if` clauses which follow it.
|
||||
For example, this listcomp combines the elements of two lists if they are not
|
||||
equal::
|
||||
|
||||
|
@ -330,12 +330,12 @@ See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
|
|||
|
||||
.. _tut-del:
|
||||
|
||||
The :keyword:`del` statement
|
||||
============================
|
||||
The :keyword:`!del` statement
|
||||
=============================
|
||||
|
||||
There is a way to remove an item from a list given its index instead of its
|
||||
value: the :keyword:`del` statement. This differs from the :meth:`pop` method
|
||||
which returns a value. The :keyword:`del` statement can also be used to remove
|
||||
which returns a value. The :keyword:`!del` statement can also be used to remove
|
||||
slices from a list or clear the entire list (which we did earlier by assignment
|
||||
of an empty list to the slice). For example::
|
||||
|
||||
|
|
|
@ -114,7 +114,7 @@ The :keyword:`try` statement works as follows.
|
|||
A :keyword:`try` statement may have more than one except clause, to specify
|
||||
handlers for different exceptions. At most one handler will be executed.
|
||||
Handlers only handle exceptions that occur in the corresponding try clause, not
|
||||
in other handlers of the same :keyword:`try` statement. An except clause may
|
||||
in other handlers of the same :keyword:`!try` statement. An except clause may
|
||||
name multiple exceptions as a parenthesized tuple, for example::
|
||||
|
||||
... except (RuntimeError, TypeError, NameError):
|
||||
|
@ -180,10 +180,10 @@ example::
|
|||
print(arg, 'has', len(f.readlines()), 'lines')
|
||||
f.close()
|
||||
|
||||
The use of the :keyword:`else` clause is better than adding additional code to
|
||||
The use of the :keyword:`!else` clause is better than adding additional code to
|
||||
the :keyword:`try` clause because it avoids accidentally catching an exception
|
||||
that wasn't raised by the code being protected by the :keyword:`try` ...
|
||||
:keyword:`except` statement.
|
||||
that wasn't raised by the code being protected by the :keyword:`!try` ...
|
||||
:keyword:`!except` statement.
|
||||
|
||||
When an exception occurs, it may have an associated value, also known as the
|
||||
exception's *argument*. The presence and type of the argument depend on the
|
||||
|
@ -343,11 +343,11 @@ example::
|
|||
|
||||
A *finally clause* is always executed before leaving the :keyword:`try`
|
||||
statement, whether an exception has occurred or not. When an exception has
|
||||
occurred in the :keyword:`try` clause and has not been handled by an
|
||||
:keyword:`except` clause (or it has occurred in an :keyword:`except` or
|
||||
:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
|
||||
been executed. The :keyword:`finally` clause is also executed "on the way out"
|
||||
when any other clause of the :keyword:`try` statement is left via a
|
||||
occurred in the :keyword:`!try` clause and has not been handled by an
|
||||
:keyword:`except` clause (or it has occurred in an :keyword:`!except` or
|
||||
:keyword:`!else` clause), it is re-raised after the :keyword:`finally` clause has
|
||||
been executed. The :keyword:`!finally` clause is also executed "on the way out"
|
||||
when any other clause of the :keyword:`!try` statement is left via a
|
||||
:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
|
||||
complicated example::
|
||||
|
||||
|
@ -376,7 +376,7 @@ complicated example::
|
|||
|
||||
As you can see, the :keyword:`finally` clause is executed in any event. The
|
||||
:exc:`TypeError` raised by dividing two strings is not handled by the
|
||||
:keyword:`except` clause and therefore re-raised after the :keyword:`finally`
|
||||
:keyword:`except` clause and therefore re-raised after the :keyword:`!finally`
|
||||
clause has been executed.
|
||||
|
||||
In real world applications, the :keyword:`finally` clause is useful for
|
||||
|
|
|
@ -317,7 +317,7 @@ reading and writing such files.
|
|||
It is good practice to use the :keyword:`with` keyword when dealing
|
||||
with file objects. The advantage is that the file is properly closed
|
||||
after its suite finishes, even if an exception is raised at some
|
||||
point. Using :keyword:`with` is also much shorter than writing
|
||||
point. Using :keyword:`!with` is also much shorter than writing
|
||||
equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
|
||||
|
||||
>>> with open('workfile') as f:
|
||||
|
|
|
@ -112,8 +112,8 @@ Note that in general the practice of importing ``*`` from a module or package is
|
|||
frowned upon, since it often causes poorly readable code. However, it is okay to
|
||||
use it to save typing in interactive sessions.
|
||||
|
||||
If the module name is followed by :keyword:`as`, then the name
|
||||
following :keyword:`as` is bound directly to the imported module.
|
||||
If the module name is followed by :keyword:`!as`, then the name
|
||||
following :keyword:`!as` is bound directly to the imported module.
|
||||
|
||||
::
|
||||
|
||||
|
|
|
@ -284,7 +284,7 @@ write the following to do it::
|
|||
L)
|
||||
|
||||
Because of Python's scoping rules, a default argument is used so that the
|
||||
anonymous function created by the :keyword:`lambda` statement knows what
|
||||
anonymous function created by the :keyword:`lambda` expression knows what
|
||||
substring is being searched for. List comprehensions make this cleaner::
|
||||
|
||||
sublist = [ s for s in L if string.find(s, S) != -1 ]
|
||||
|
@ -296,11 +296,11 @@ List comprehensions have the form::
|
|||
for exprN in sequenceN
|
||||
if condition ]
|
||||
|
||||
The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
|
||||
The :keyword:`!for`...\ :keyword:`!in` clauses contain the sequences to be
|
||||
iterated over. The sequences do not have to be the same length, because they
|
||||
are *not* iterated over in parallel, but from left to right; this is explained
|
||||
more clearly in the following paragraphs. The elements of the generated list
|
||||
will be the successive values of *expression*. The final :keyword:`if` clause
|
||||
will be the successive values of *expression*. The final :keyword:`!if` clause
|
||||
is optional; if present, *expression* is only evaluated and added to the result
|
||||
if *condition* is true.
|
||||
|
||||
|
@ -316,7 +316,7 @@ following Python code::
|
|||
# the expression to the
|
||||
# resulting list.
|
||||
|
||||
This means that when there are multiple :keyword:`for`...\ :keyword:`in`
|
||||
This means that when there are multiple :keyword:`!for`...\ :keyword:`!in`
|
||||
clauses, the resulting list will be equal to the product of the lengths of all
|
||||
the sequences. If you have two lists of length 3, the output list is 9 elements
|
||||
long::
|
||||
|
@ -541,8 +541,8 @@ true if *obj* is present in the sequence *seq*; Python computes this by simply
|
|||
trying every index of the sequence until either *obj* is found or an
|
||||
:exc:`IndexError` is encountered. Moshe Zadka contributed a patch which adds a
|
||||
:meth:`__contains__` magic method for providing a custom implementation for
|
||||
:keyword:`in`. Additionally, new built-in objects written in C can define what
|
||||
:keyword:`in` means for them via a new slot in the sequence protocol.
|
||||
:keyword:`!in`. Additionally, new built-in objects written in C can define what
|
||||
:keyword:`!in` means for them via a new slot in the sequence protocol.
|
||||
|
||||
Earlier versions of Python used a recursive algorithm for deleting objects.
|
||||
Deeply nested data structures could cause the interpreter to fill up the C stack
|
||||
|
|
|
@ -52,7 +52,7 @@ The function :func:`g` will always raise a :exc:`NameError` exception, because
|
|||
the binding of the name ``g`` isn't in either its local namespace or in the
|
||||
module-level namespace. This isn't much of a problem in practice (how often do
|
||||
you recursively define interior functions like this?), but this also made using
|
||||
the :keyword:`lambda` statement clumsier, and this was a problem in practice.
|
||||
the :keyword:`lambda` expression clumsier, and this was a problem in practice.
|
||||
In code which uses :keyword:`lambda` you can often find local variables being
|
||||
copied by passing them as the default values of arguments. ::
|
||||
|
||||
|
@ -143,7 +143,7 @@ The syntax uses a ``from...import`` statement using the reserved module name
|
|||
While it looks like a normal :keyword:`import` statement, it's not; there are
|
||||
strict rules on where such a future statement can be put. They can only be at
|
||||
the top of a module, and must precede any Python code or regular
|
||||
:keyword:`import` statements. This is because such statements can affect how
|
||||
:keyword:`!import` statements. This is because such statements can affect how
|
||||
the Python bytecode compiler parses code and generates bytecode, so they must
|
||||
precede any statement that will result in bytecodes being produced.
|
||||
|
||||
|
|
|
@ -121,7 +121,7 @@ added so if no built-in type is suitable, you can just subclass
|
|||
This means that :keyword:`class` statements that don't have any base classes are
|
||||
always classic classes in Python 2.2. (Actually you can also change this by
|
||||
setting a module-level variable named :attr:`__metaclass__` --- see :pep:`253`
|
||||
for the details --- but it's easier to just subclass :keyword:`object`.)
|
||||
for the details --- but it's easier to just subclass :class:`object`.)
|
||||
|
||||
The type objects for the built-in types are available as built-ins, named using
|
||||
a clever trick. Python has always had built-in functions named :func:`int`,
|
||||
|
@ -560,7 +560,7 @@ Here's the simplest example of a generator function::
|
|||
yield i
|
||||
|
||||
A new keyword, :keyword:`yield`, was introduced for generators. Any function
|
||||
containing a :keyword:`yield` statement is a generator function; this is
|
||||
containing a :keyword:`!yield` statement is a generator function; this is
|
||||
detected by Python's bytecode compiler which compiles the function specially as
|
||||
a result. Because a new keyword was introduced, generators must be explicitly
|
||||
enabled in a module by including a ``from __future__ import generators``
|
||||
|
@ -571,14 +571,14 @@ When you call a generator function, it doesn't return a single value; instead it
|
|||
returns a generator object that supports the iterator protocol. On executing
|
||||
the :keyword:`yield` statement, the generator outputs the value of ``i``,
|
||||
similar to a :keyword:`return` statement. The big difference between
|
||||
:keyword:`yield` and a :keyword:`return` statement is that on reaching a
|
||||
:keyword:`yield` the generator's state of execution is suspended and local
|
||||
:keyword:`!yield` and a :keyword:`!return` statement is that on reaching a
|
||||
:keyword:`!yield` the generator's state of execution is suspended and local
|
||||
variables are preserved. On the next call to the generator's ``next()`` method,
|
||||
the function will resume executing immediately after the :keyword:`yield`
|
||||
statement. (For complicated reasons, the :keyword:`yield` statement isn't
|
||||
allowed inside the :keyword:`try` block of a
|
||||
the function will resume executing immediately after the :keyword:`!yield`
|
||||
statement. (For complicated reasons, the :keyword:`!yield` statement isn't
|
||||
allowed inside the :keyword:`!try` block of a
|
||||
:keyword:`try`...\ :keyword:`finally` statement; read :pep:`255` for a full
|
||||
explanation of the interaction between :keyword:`yield` and exceptions.)
|
||||
explanation of the interaction between :keyword:`!yield` and exceptions.)
|
||||
|
||||
Here's a sample usage of the :func:`generate_ints` generator::
|
||||
|
||||
|
@ -602,7 +602,7 @@ generate_ints(3)``.
|
|||
|
||||
Inside a generator function, the :keyword:`return` statement can only be used
|
||||
without a value, and signals the end of the procession of values; afterwards the
|
||||
generator cannot return any further values. :keyword:`return` with a value, such
|
||||
generator cannot return any further values. :keyword:`!return` with a value, such
|
||||
as ``return 5``, is a syntax error inside a generator function. The end of the
|
||||
generator's results can also be indicated by raising :exc:`StopIteration`
|
||||
manually, or by just letting the flow of execution fall off the bottom of the
|
||||
|
@ -863,8 +863,8 @@ The function :func:`g` will always raise a :exc:`NameError` exception, because
|
|||
the binding of the name ``g`` isn't in either its local namespace or in the
|
||||
module-level namespace. This isn't much of a problem in practice (how often do
|
||||
you recursively define interior functions like this?), but this also made using
|
||||
the :keyword:`lambda` statement clumsier, and this was a problem in practice.
|
||||
In code which uses :keyword:`lambda` you can often find local variables being
|
||||
the :keyword:`lambda` expression clumsier, and this was a problem in practice.
|
||||
In code which uses :keyword:`!lambda` you can often find local variables being
|
||||
copied by passing them as the default values of arguments. ::
|
||||
|
||||
def find(self, name):
|
||||
|
|
|
@ -149,7 +149,7 @@ Here's the simplest example of a generator function::
|
|||
yield i
|
||||
|
||||
A new keyword, :keyword:`yield`, was introduced for generators. Any function
|
||||
containing a :keyword:`yield` statement is a generator function; this is
|
||||
containing a :keyword:`!yield` statement is a generator function; this is
|
||||
detected by Python's bytecode compiler which compiles the function specially as
|
||||
a result.
|
||||
|
||||
|
@ -157,14 +157,14 @@ When you call a generator function, it doesn't return a single value; instead it
|
|||
returns a generator object that supports the iterator protocol. On executing
|
||||
the :keyword:`yield` statement, the generator outputs the value of ``i``,
|
||||
similar to a :keyword:`return` statement. The big difference between
|
||||
:keyword:`yield` and a :keyword:`return` statement is that on reaching a
|
||||
:keyword:`yield` the generator's state of execution is suspended and local
|
||||
:keyword:`!yield` and a :keyword:`!return` statement is that on reaching a
|
||||
:keyword:`!yield` the generator's state of execution is suspended and local
|
||||
variables are preserved. On the next call to the generator's ``.next()``
|
||||
method, the function will resume executing immediately after the
|
||||
:keyword:`yield` statement. (For complicated reasons, the :keyword:`yield`
|
||||
:keyword:`!yield` statement. (For complicated reasons, the :keyword:`!yield`
|
||||
statement isn't allowed inside the :keyword:`try` block of a
|
||||
:keyword:`try`...\ :keyword:`finally` statement; read :pep:`255` for a full
|
||||
explanation of the interaction between :keyword:`yield` and exceptions.)
|
||||
:keyword:`!try`...\ :keyword:`!finally` statement; read :pep:`255` for a full
|
||||
explanation of the interaction between :keyword:`!yield` and exceptions.)
|
||||
|
||||
Here's a sample usage of the :func:`generate_ints` generator::
|
||||
|
||||
|
@ -188,7 +188,7 @@ generate_ints(3)``.
|
|||
|
||||
Inside a generator function, the :keyword:`return` statement can only be used
|
||||
without a value, and signals the end of the procession of values; afterwards the
|
||||
generator cannot return any further values. :keyword:`return` with a value, such
|
||||
generator cannot return any further values. :keyword:`!return` with a value, such
|
||||
as ``return 5``, is a syntax error inside a generator function. The end of the
|
||||
generator's results can also be indicated by raising :exc:`StopIteration`
|
||||
manually, or by just letting the flow of execution fall off the bottom of the
|
||||
|
@ -589,7 +589,7 @@ strict language such as Pascal would also prevent you performing arithmetic with
|
|||
Booleans, and would require that the expression in an :keyword:`if` statement
|
||||
always evaluate to a Boolean result. Python is not this strict and never will
|
||||
be, as :pep:`285` explicitly says. This means you can still use any expression
|
||||
in an :keyword:`if` statement, even ones that evaluate to a list or tuple or
|
||||
in an :keyword:`!if` statement, even ones that evaluate to a list or tuple or
|
||||
some random object. The Boolean type is a subclass of the :class:`int` class so
|
||||
that arithmetic using a Boolean still works. ::
|
||||
|
||||
|
|
|
@ -370,7 +370,7 @@ PEP 341: Unified try/except/finally
|
|||
Until Python 2.5, the :keyword:`try` statement came in two flavours. You could
|
||||
use a :keyword:`finally` block to ensure that code is always executed, or one or
|
||||
more :keyword:`except` blocks to catch specific exceptions. You couldn't
|
||||
combine both :keyword:`except` blocks and a :keyword:`finally` block, because
|
||||
combine both :keyword:`!except` blocks and a :keyword:`!finally` block, because
|
||||
generating the right bytecode for the combined version was complicated and it
|
||||
wasn't clear what the semantics of the combined statement should be.
|
||||
|
||||
|
@ -435,10 +435,10 @@ When you call ``counter(10)``, the result is an iterator that returns the values
|
|||
from 0 up to 9. On encountering the :keyword:`yield` statement, the iterator
|
||||
returns the provided value and suspends the function's execution, preserving the
|
||||
local variables. Execution resumes on the following call to the iterator's
|
||||
:meth:`next` method, picking up after the :keyword:`yield` statement.
|
||||
:meth:`next` method, picking up after the :keyword:`!yield` statement.
|
||||
|
||||
In Python 2.3, :keyword:`yield` was a statement; it didn't return any value. In
|
||||
2.5, :keyword:`yield` is now an expression, returning a value that can be
|
||||
2.5, :keyword:`!yield` is now an expression, returning a value that can be
|
||||
assigned to a variable or otherwise operated on::
|
||||
|
||||
val = (yield i)
|
||||
|
@ -458,7 +458,7 @@ expression on the right-hand side of an assignment. This means you can write
|
|||
Values are sent into a generator by calling its ``send(value)`` method. The
|
||||
generator's code is then resumed and the :keyword:`yield` expression returns the
|
||||
specified *value*. If the regular :meth:`next` method is called, the
|
||||
:keyword:`yield` returns :const:`None`.
|
||||
:keyword:`!yield` returns :const:`None`.
|
||||
|
||||
Here's the previous example, modified to allow changing the value of the
|
||||
internal counter. ::
|
||||
|
@ -644,7 +644,7 @@ Writing Context Managers
|
|||
------------------------
|
||||
|
||||
Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
|
||||
people will only use ':keyword:`with`' in company with existing objects and
|
||||
people will only use ':keyword:`!with`' in company with existing objects and
|
||||
don't need to know these details, so you can skip the rest of this section if
|
||||
you like. Authors of new objects will need to understand the details of the
|
||||
underlying implementation and should keep reading.
|
||||
|
@ -750,9 +750,9 @@ generator function instead of defining a new class. The generator should yield
|
|||
exactly one value. The code up to the :keyword:`yield` will be executed as the
|
||||
:meth:`__enter__` method, and the value yielded will be the method's return
|
||||
value that will get bound to the variable in the ':keyword:`with`' statement's
|
||||
:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
|
||||
:keyword:`!as` clause, if any. The code after the :keyword:`yield` will be
|
||||
executed in the :meth:`__exit__` method. Any exception raised in the block will
|
||||
be raised by the :keyword:`yield` statement.
|
||||
be raised by the :keyword:`!yield` statement.
|
||||
|
||||
Our database example from the previous section could be written using this
|
||||
decorator as::
|
||||
|
@ -776,7 +776,7 @@ decorator as::
|
|||
|
||||
The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function
|
||||
that combines a number of context managers so you don't need to write nested
|
||||
':keyword:`with`' statements. In this example, the single ':keyword:`with`'
|
||||
':keyword:`with`' statements. In this example, the single ':keyword:`!with`'
|
||||
statement both starts a database transaction and acquires a thread lock::
|
||||
|
||||
lock = threading.Lock()
|
||||
|
|
|
@ -250,10 +250,10 @@ PEP 343: The 'with' statement
|
|||
The previous version, Python 2.5, added the ':keyword:`with`'
|
||||
statement as an optional feature, to be enabled by a ``from __future__
|
||||
import with_statement`` directive. In 2.6 the statement no longer needs to
|
||||
be specially enabled; this means that :keyword:`with` is now always a
|
||||
be specially enabled; this means that :keyword:`!with` is now always a
|
||||
keyword. The rest of this section is a copy of the corresponding
|
||||
section from the "What's New in Python 2.5" document; if you're
|
||||
familiar with the ':keyword:`with`' statement
|
||||
familiar with the ':keyword:`!with`' statement
|
||||
from Python 2.5, you can skip this section.
|
||||
|
||||
The ':keyword:`with`' statement clarifies code that previously would use
|
||||
|
@ -331,7 +331,7 @@ Writing Context Managers
|
|||
------------------------
|
||||
|
||||
Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
|
||||
people will only use ':keyword:`with`' in company with existing objects and
|
||||
people will only use ':keyword:`!with`' in company with existing objects and
|
||||
don't need to know these details, so you can skip the rest of this section if
|
||||
you like. Authors of new objects will need to understand the details of the
|
||||
underlying implementation and should keep reading.
|
||||
|
@ -438,9 +438,9 @@ generator function instead of defining a new class. The generator should yield
|
|||
exactly one value. The code up to the :keyword:`yield` will be executed as the
|
||||
:meth:`__enter__` method, and the value yielded will be the method's return
|
||||
value that will get bound to the variable in the ':keyword:`with`' statement's
|
||||
:keyword:`as` clause, if any. The code after the :keyword:`yield` will be
|
||||
:keyword:`!as` clause, if any. The code after the :keyword:`!yield` will be
|
||||
executed in the :meth:`__exit__` method. Any exception raised in the block will
|
||||
be raised by the :keyword:`yield` statement.
|
||||
be raised by the :keyword:`!yield` statement.
|
||||
|
||||
Using this decorator, our database example from the previous section
|
||||
could be written as::
|
||||
|
@ -464,7 +464,7 @@ could be written as::
|
|||
|
||||
The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function
|
||||
that combines a number of context managers so you don't need to write nested
|
||||
':keyword:`with`' statements. In this example, the single ':keyword:`with`'
|
||||
':keyword:`with`' statements. In this example, the single ':keyword:`!with`'
|
||||
statement both starts a database transaction and acquires a thread lock::
|
||||
|
||||
lock = threading.Lock()
|
||||
|
@ -1684,7 +1684,7 @@ Some smaller changes made to the core Python language are:
|
|||
* An obscure change: when you use the :func:`locals` function inside a
|
||||
:keyword:`class` statement, the resulting dictionary no longer returns free
|
||||
variables. (Free variables, in this case, are variables referenced in the
|
||||
:keyword:`class` statement that aren't attributes of the class.)
|
||||
:keyword:`!class` statement that aren't attributes of the class.)
|
||||
|
||||
.. ======================================================================
|
||||
|
||||
|
|
|
@ -708,7 +708,7 @@ Some smaller changes made to the core Python language are:
|
|||
|
||||
* The :keyword:`with` statement can now use multiple context managers
|
||||
in one statement. Context managers are processed from left to right
|
||||
and each one is treated as beginning a new :keyword:`with` statement.
|
||||
and each one is treated as beginning a new :keyword:`!with` statement.
|
||||
This means that::
|
||||
|
||||
with A() as a, B() as b:
|
||||
|
@ -844,7 +844,7 @@ Some smaller changes made to the core Python language are:
|
|||
|
||||
* The :keyword:`import` statement will no longer try an absolute import
|
||||
if a relative import (e.g. ``from .os import sep``) fails. This
|
||||
fixes a bug, but could possibly break certain :keyword:`import`
|
||||
fixes a bug, but could possibly break certain :keyword:`!import`
|
||||
statements that were only working by accident. (Fixed by Meador Inge;
|
||||
:issue:`7902`.)
|
||||
|
||||
|
@ -1158,7 +1158,7 @@ changes, or look through the Subversion logs for all the details.
|
|||
|
||||
* Deprecated function: :func:`contextlib.nested`, which allows
|
||||
handling more than one context manager with a single :keyword:`with`
|
||||
statement, has been deprecated, because the :keyword:`with` statement
|
||||
statement, has been deprecated, because the :keyword:`!with` statement
|
||||
now supports multiple context managers.
|
||||
|
||||
* The :mod:`cookielib` module now ignores cookies that have an invalid
|
||||
|
|
|
@ -373,7 +373,7 @@ New Syntax
|
|||
|
||||
* :pep:`3104`: :keyword:`nonlocal` statement. Using ``nonlocal x``
|
||||
you can now assign directly to a variable in an outer (but
|
||||
non-global) scope. :keyword:`nonlocal` is a new reserved word.
|
||||
non-global) scope. :keyword:`!nonlocal` is a new reserved word.
|
||||
|
||||
* :pep:`3132`: Extended Iterable Unpacking. You can now write things
|
||||
like ``a, b, *rest = some_sequence``. And even ``*rest, a =
|
||||
|
@ -408,14 +408,14 @@ Changed Syntax
|
|||
* :pep:`3109` and :pep:`3134`: new :keyword:`raise` statement syntax:
|
||||
:samp:`raise [{expr} [from {expr}]]`. See below.
|
||||
|
||||
* :keyword:`as` and :keyword:`with` are now reserved words. (Since
|
||||
* :keyword:`!as` and :keyword:`with` are now reserved words. (Since
|
||||
2.6, actually.)
|
||||
|
||||
* ``True``, ``False``, and ``None`` are reserved words. (2.6 partially enforced
|
||||
the restrictions on ``None`` already.)
|
||||
|
||||
* Change from :keyword:`except` *exc*, *var* to
|
||||
:keyword:`except` *exc* :keyword:`as` *var*. See :pep:`3110`.
|
||||
:keyword:`!except` *exc* :keyword:`!as` *var*. See :pep:`3110`.
|
||||
|
||||
* :pep:`3115`: New Metaclass Syntax. Instead of::
|
||||
|
||||
|
@ -507,9 +507,9 @@ consulted for longer descriptions.
|
|||
* :ref:`pep-3105`. This is now a standard feature and no longer needs
|
||||
to be imported from :mod:`__future__`. More details were given above.
|
||||
|
||||
* :ref:`pep-3110`. The :keyword:`except` *exc* :keyword:`as` *var*
|
||||
syntax is now standard and :keyword:`except` *exc*, *var* is no
|
||||
longer supported. (Of course, the :keyword:`as` *var* part is still
|
||||
* :ref:`pep-3110`. The :keyword:`except` *exc* :keyword:`!as` *var*
|
||||
syntax is now standard and :keyword:`!except` *exc*, *var* is no
|
||||
longer supported. (Of course, the :keyword:`!as` *var* part is still
|
||||
optional.)
|
||||
|
||||
* :ref:`pep-3112`. The ``b"..."`` string literal notation (and its
|
||||
|
|
|
@ -1352,7 +1352,7 @@ shelve
|
|||
------
|
||||
|
||||
:class:`~shelve.Shelf` instances may now be used in :keyword:`with` statements,
|
||||
and will be automatically closed at the end of the :keyword:`with` block.
|
||||
and will be automatically closed at the end of the :keyword:`!with` block.
|
||||
(Contributed by Filip Gruszczyński in :issue:`13896`.)
|
||||
|
||||
|
||||
|
|
|
@ -1896,7 +1896,7 @@ Deprecated Python Behavior
|
|||
|
||||
Yield expressions (both ``yield`` and ``yield from`` clauses) are now deprecated
|
||||
in comprehensions and generator expressions (aside from the iterable expression
|
||||
in the leftmost :keyword:`for` clause). This ensures that comprehensions
|
||||
in the leftmost :keyword:`!for` clause). This ensures that comprehensions
|
||||
always immediately return a container of the appropriate type (rather than
|
||||
potentially returning a :term:`generator iterator` object), while generator
|
||||
expressions won't attempt to interleave their implicit output with the output
|
||||
|
|
|
@ -415,7 +415,7 @@ Changes in Python behavior
|
|||
|
||||
* Yield expressions (both ``yield`` and ``yield from`` clauses) are now disallowed
|
||||
in comprehensions and generator expressions (aside from the iterable expression
|
||||
in the leftmost :keyword:`for` clause).
|
||||
in the leftmost :keyword:`!for` clause).
|
||||
(Contributed by Serhiy Storchaka in :issue:`10544`.)
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue