Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
2b57c43f
Commit
2b57c43f
authored
Dec 19, 2018
by
Serhiy Storchaka
Committed by
GitHub
Dec 19, 2018
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
bpo-35506: Remove redundant and incorrect links from keywords. (GH-11174)
parent
82d73554
Changes
45
Show whitespace changes
Inline
Side-by-side
Showing
45 changed files
with
240 additions
and
242 deletions
+240
-242
Doc/faq/programming.rst
Doc/faq/programming.rst
+1
-1
Doc/glossary.rst
Doc/glossary.rst
+3
-3
Doc/howto/functional.rst
Doc/howto/functional.rst
+1
-1
Doc/library/aifc.rst
Doc/library/aifc.rst
+1
-1
Doc/library/contextlib.rst
Doc/library/contextlib.rst
+7
-7
Doc/library/fileinput.rst
Doc/library/fileinput.rst
+2
-2
Doc/library/functions.rst
Doc/library/functions.rst
+1
-1
Doc/library/imaplib.rst
Doc/library/imaplib.rst
+1
-1
Doc/library/imp.rst
Doc/library/imp.rst
+1
-1
Doc/library/importlib.rst
Doc/library/importlib.rst
+4
-4
Doc/library/io.rst
Doc/library/io.rst
+1
-1
Doc/library/parser.rst
Doc/library/parser.rst
+1
-1
Doc/library/pickle.rst
Doc/library/pickle.rst
+1
-1
Doc/library/smtplib.rst
Doc/library/smtplib.rst
+1
-1
Doc/library/socketserver.rst
Doc/library/socketserver.rst
+1
-1
Doc/library/stdtypes.rst
Doc/library/stdtypes.rst
+6
-6
Doc/library/telnetlib.rst
Doc/library/telnetlib.rst
+1
-1
Doc/library/tempfile.rst
Doc/library/tempfile.rst
+1
-1
Doc/library/threading.rst
Doc/library/threading.rst
+2
-2
Doc/library/wave.rst
Doc/library/wave.rst
+1
-1
Doc/library/xml.dom.minidom.rst
Doc/library/xml.dom.minidom.rst
+1
-1
Doc/library/zipfile.rst
Doc/library/zipfile.rst
+1
-1
Doc/reference/compound_stmts.rst
Doc/reference/compound_stmts.rst
+35
-39
Doc/reference/datamodel.rst
Doc/reference/datamodel.rst
+4
-4
Doc/reference/executionmodel.rst
Doc/reference/executionmodel.rst
+3
-3
Doc/reference/expressions.rst
Doc/reference/expressions.rst
+22
-20
Doc/reference/import.rst
Doc/reference/import.rst
+3
-3
Doc/reference/simple_stmts.rst
Doc/reference/simple_stmts.rst
+43
-43
Doc/tutorial/classes.rst
Doc/tutorial/classes.rst
+1
-1
Doc/tutorial/controlflow.rst
Doc/tutorial/controlflow.rst
+17
-17
Doc/tutorial/datastructures.rst
Doc/tutorial/datastructures.rst
+5
-5
Doc/tutorial/errors.rst
Doc/tutorial/errors.rst
+10
-10
Doc/tutorial/inputoutput.rst
Doc/tutorial/inputoutput.rst
+1
-1
Doc/tutorial/modules.rst
Doc/tutorial/modules.rst
+2
-2
Doc/whatsnew/2.0.rst
Doc/whatsnew/2.0.rst
+6
-6
Doc/whatsnew/2.1.rst
Doc/whatsnew/2.1.rst
+2
-2
Doc/whatsnew/2.2.rst
Doc/whatsnew/2.2.rst
+11
-11
Doc/whatsnew/2.3.rst
Doc/whatsnew/2.3.rst
+8
-8
Doc/whatsnew/2.5.rst
Doc/whatsnew/2.5.rst
+8
-8
Doc/whatsnew/2.6.rst
Doc/whatsnew/2.6.rst
+7
-7
Doc/whatsnew/2.7.rst
Doc/whatsnew/2.7.rst
+3
-3
Doc/whatsnew/3.0.rst
Doc/whatsnew/3.0.rst
+6
-6
Doc/whatsnew/3.4.rst
Doc/whatsnew/3.4.rst
+1
-1
Doc/whatsnew/3.7.rst
Doc/whatsnew/3.7.rst
+1
-1
Doc/whatsnew/3.8.rst
Doc/whatsnew/3.8.rst
+1
-1
No files found.
Doc/faq/programming.rst
View file @
2b57c43f
...
@@ -738,7 +738,7 @@ Is it possible to write obfuscated one-liners in Python?
...
@@ -738,7 +738,7 @@ Is it possible to write obfuscated one-liners in Python?
--------------------------------------------------------
--------------------------------------------------------
Yes. Usually this is done by nesting :keyword:`lambda` within
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
from functools import reduce
...
...
Doc/glossary.rst
View file @
2b57c43f
...
@@ -336,7 +336,7 @@ Glossary
...
@@ -336,7 +336,7 @@ Glossary
names
,
attribute
access
,
operators
or
function
calls
which
all
return
a
names
,
attribute
access
,
operators
or
function
calls
which
all
return
a
value
.
In
contrast
to
many
other
languages
,
not
all
language
constructs
value
.
In
contrast
to
many
other
languages
,
not
all
language
constructs
are
expressions
.
There
are
also
:
term
:`
statement
`\
s
which
cannot
be
used
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
.
not
expressions
.
extension
module
extension
module
...
@@ -448,8 +448,8 @@ Glossary
...
@@ -448,8 +448,8 @@ Glossary
generator
expression
generator
expression
An
expression
that
returns
an
iterator
.
It
looks
like
a
normal
expression
An
expression
that
returns
an
iterator
.
It
looks
like
a
normal
expression
followed
by
a
:
keyword
:`
for
`
expression
defining
a
loop
variable
,
range
,
followed
by
a
:
keyword
:`
!for` clause
defining a loop variable, range,
and
an
optional
:
keyword
:`
if
`
expression
.
The
combined
expression
and
an
optional
:
keyword
:`
!if` clause
. The combined expression
generates
values
for
an
enclosing
function
::
generates
values
for
an
enclosing
function
::
>>>
sum
(
i
*
i
for
i
in
range
(
10
))
#
sum
of
squares
0
,
1
,
4
,
...
81
>>>
sum
(
i
*
i
for
i
in
range
(
10
))
#
sum
of
squares
0
,
1
,
4
,
...
81
...
...
Doc/howto/functional.rst
View file @
2b57c43f
...
@@ -1108,7 +1108,7 @@ need to define a new function at all::
...
@@ -1108,7 +1108,7 @@ need to define a new function at all::
existing_files = filter(os.path.exists, file_list)
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
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
number of parameters and an expression combining these parameters, and creates
an anonymous function that returns the value of the expression::
an anonymous function that returns the value of the expression::
...
...
Doc/library/aifc.rst
View file @
2b57c43f
...
@@ -45,7 +45,7 @@ Module :mod:`aifc` defines the following function:
...
@@ -45,7 +45,7 @@ Module :mod:`aifc` defines the following function:
time how many samples you are going to write in total and use
time how many samples you are going to write in total and use
:meth:`writeframesraw` and :meth:`setnframes`.
:meth:`writeframesraw` and :meth:`setnframes`.
The :func:`.open` function may be used in a :keyword:`with` statement. When
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
.. versionchanged:: 3.4
Support for the :keyword:`with` statement was added.
Support for the :keyword:`with` statement was added.
...
...
Doc/library/contextlib.rst
View file @
2b57c43f
:mod:`
contextlib` --- Utilities for :keyword:`
with`\ -statement contexts
:mod:`
!contextlib` --- Utilities for :keyword:`!
with`\ -statement contexts
========================================================================
========================================================================
==
.. module:: contextlib
.. module:: contextlib
:synopsis: Utilities for with-statement contexts.
:synopsis: Utilities for with-statement contexts.
...
@@ -72,7 +72,7 @@ Functions and classes provided:
...
@@ -72,7 +72,7 @@ Functions and classes provided:
The function being decorated must return a :term:`generator`-iterator when
The function being decorated must return a :term:`generator`-iterator when
called. This iterator must yield exactly one value, which will be bound to
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`
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.
statement is executed. The generator is then resumed after the block is exited.
...
@@ -82,9 +82,9 @@ Functions and classes provided:
...
@@ -82,9 +82,9 @@ Functions and classes provided:
the error (if any), or ensure that some cleanup takes place. If an exception is
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
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
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
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
:func:`contextmanager` uses :class:`ContextDecorator` so the context managers
it creates can be used as decorators as well as in :keyword:`with` statements.
it creates can be used as decorators as well as in :keyword:`with` statements.
...
@@ -346,7 +346,7 @@ Functions and classes provided:
...
@@ -346,7 +346,7 @@ Functions and classes provided:
As the decorated function must be able to be called multiple times, the
As the decorated function must be able to be called multiple times, the
underlying context manager must support use in multiple :keyword:`with`
underlying context manager must support use in multiple :keyword:`with`
statements. If this is not the case, then the original construct with the
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
.. versionadded:: 3.2
...
@@ -771,7 +771,7 @@ Reentrant context managers
...
@@ -771,7 +771,7 @@ Reentrant context managers
More sophisticated context managers may be "reentrant". These context
More sophisticated context managers may be "reentrant". These context
managers can not only be used in multiple :keyword:`with` statements,
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.
using the same context manager.
:class:`threading.RLock` is an example of a reentrant context manager, as are
:class:`threading.RLock` is an example of a reentrant context manager, as are
...
...
Doc/library/fileinput.rst
View file @
2b57c43f
...
@@ -63,7 +63,7 @@ The following function is the primary interface of this module:
...
@@ -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
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. 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:
with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
for line in f:
for line in f:
...
@@ -155,7 +155,7 @@ available for subclassing as well:
...
@@ -155,7 +155,7 @@ available for subclassing as well:
A :class:`FileInput` instance can be used as a context manager in the
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. 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:
with FileInput(files=('spam.txt', 'eggs.txt')) as input:
process(input)
process(input)
...
...
Doc/library/functions.rst
View file @
2b57c43f
...
@@ -1665,7 +1665,7 @@ are always available. They are listed here in alphabetical order.
...
@@ -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
This function is invoked by the :keyword:`import` statement. It can be
replaced (by importing the :mod:`builtins` module and assigning to
replaced (by importing the :mod:`builtins` module and assigning to
``builtins.__import__``) in order to change semantics of the
``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
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
goals and does not cause issues with code which assumes the default import
implementation is in use. Direct use of :func:`__import__` is also
implementation is in use. Direct use of :func:`__import__` is also
...
...
Doc/library/imaplib.rst
View file @
2b57c43f
...
@@ -39,7 +39,7 @@ base class:
...
@@ -39,7 +39,7 @@ base class:
The :class:`IMAP4` class supports the :keyword:`with` statement. When used
The :class:`IMAP4` class supports the :keyword:`with` statement. When used
like this, the IMAP4 ``LOGOUT`` command is issued automatically when the
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
>>> from imaplib import IMAP4
>>> with IMAP4("domain.org") as M:
>>> with IMAP4("domain.org") as M:
...
...
Doc/library/imp.rst
View file @
2b57c43f
...
@@ -179,7 +179,7 @@ This module provides an interface to the mechanisms used to implement the
...
@@ -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` ...
If a module imports objects from another module using :keyword:`from` ...
:keyword:`import` ..., calling :func:`reload` for the other module does not
: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
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.
names (*module*.*name*) instead.
If a module instantiates instances of a class, reloading the module that defines
If a module instantiates instances of a class, reloading the module that defines
...
...
Doc/library/importlib.rst
View file @
2b57c43f
:
mod
:`
importlib
`
---
The
implementation
of
:
keyword
:`
import
`
:
mod
:`
!importlib` --- The implementation of :keyword:`!
import`
============================================================
============================================================
==
..
module
::
importlib
..
module
::
importlib
:
synopsis
:
The
implementation
of
the
import
machinery
.
:
synopsis
:
The
implementation
of
the
import
machinery
.
...
@@ -19,7 +19,7 @@ Introduction
...
@@ -19,7 +19,7 @@ Introduction
The
purpose
of
the
:
mod
:`
importlib
`
package
is
two
-
fold
.
One
is
to
provide
the
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
implementation
of
the
:
keyword
:`
import
`
statement
(
and
thus
,
by
extension
,
the
:
func
:`
__import__
`
function
)
in
Python
source
code
.
This
provides
an
:
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
interpreter
.
This
also
provides
an
implementation
which
is
easier
to
comprehend
than
one
implemented
in
a
programming
language
other
than
Python
.
comprehend
than
one
implemented
in
a
programming
language
other
than
Python
.
...
@@ -197,7 +197,7 @@ Functions
...
@@ -197,7 +197,7 @@ Functions
If
a
module
imports
objects
from
another
module
using
:
keyword
:`
from
`
...
If
a
module
imports
objects
from
another
module
using
:
keyword
:`
from
`
...
:
keyword
:`
import
`
...,
calling
:
func
:`
reload
`
for
the
other
module
does
not
:
keyword
:`
import
`
...,
calling
:
func
:`
reload
`
for
the
other
module
does
not
redefine
the
objects
imported
from
it
---
one
way
around
this
is
to
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
.
and
qualified
names
(*
module
.
name
*)
instead
.
If
a
module
instantiates
instances
of
a
class
,
reloading
the
module
that
If
a
module
instantiates
instances
of
a
class
,
reloading
the
module
that
...
...
Doc/library/io.rst
View file @
2b57c43f
...
@@ -249,7 +249,7 @@ I/O Base Classes
...
@@ -249,7 +249,7 @@ I/O Base Classes
:class:`IOBase` is also a context manager and therefore supports the
: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. 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:
with open('spam.txt', 'w') as file:
file.write('Spam and eggs!')
file.write('Spam and eggs!')
...
...
Doc/library/parser.rst
View file @
2b57c43f
...
@@ -63,7 +63,7 @@ of the production as recognized in the input string: these are always sequences
...
@@ -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 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,
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
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
is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value
associated with all :const:`NAME` tokens, including variable and function names
associated with all :const:`NAME` tokens, including variable and function names
defined by the user. In an alternate form returned when line number information
defined by the user. In an alternate form returned when line number information
...
...
Doc/library/pickle.rst
View file @
2b57c43f
...
@@ -931,7 +931,7 @@ The following example reads the resulting pickled data. ::
...
@@ -931,7 +931,7 @@ The following example reads the resulting pickled data. ::
.. [#] Don't confuse this with the :mod:`marshal` module
.. [#] Don't confuse this with the :mod:`marshal` module
.. [#] This is why :keyword:`lambda` functions cannot be pickled: all
.. [#] 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
.. [#] The exception raised will likely be an :exc:`ImportError` or an
:exc:`AttributeError` but it could be something else.
:exc:`AttributeError` but it could be something else.
...
...
Doc/library/smtplib.rst
View file @
2b57c43f
...
@@ -46,7 +46,7 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
...
@@ -46,7 +46,7 @@ Protocol) and :rfc:`1869` (SMTP Service Extensions).
The :class:`SMTP` class supports the :keyword:`with` statement. When used
The :class:`SMTP` class supports the :keyword:`with` statement. When used
like this, the SMTP ``QUIT`` command is issued automatically when the
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
>>> from smtplib import SMTP
>>> with SMTP("domain.org") as smtp:
>>> with SMTP("domain.org") as smtp:
...
...
Doc/library/socketserver.rst
View file @
2b57c43f
...
@@ -57,7 +57,7 @@ the server in a :keyword:`with` statement. Then call the
...
@@ -57,7 +57,7 @@ the server in a :keyword:`with` statement. Then call the
:meth:`~BaseServer.handle_request` or
:meth:`~BaseServer.handle_request` or
:meth:`~BaseServer.serve_forever` method of the server object to
:meth:`~BaseServer.serve_forever` method of the server object to
process one or many requests. Finally, call :meth:`~BaseServer.server_close`
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,
When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
you should explicitly declare how you want your threads to behave on an abrupt
you should explicitly declare how you want your threads to behave on an abrupt
...
...
Doc/library/stdtypes.rst
View file @
2b57c43f
...
@@ -74,8 +74,8 @@ one of their operands.)
...
@@ -74,8 +74,8 @@ one of their operands.)
.. _boolean:
.. _boolean:
Boolean Operations --- :keyword:`
and`, :keyword:`or`, :keyword:`
not`
Boolean Operations --- :keyword:`
!and`, :keyword:`!or`, :keyword:`!
not`
====================================================================
====================================================================
===
.. index:: pair: Boolean; operations
.. index:: pair: Boolean; operations
...
@@ -4460,7 +4460,7 @@ before the statement body is executed and exited when the statement ends:
...
@@ -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
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
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.
this context manager.
An example of a context manager that returns itself is a :term:`file object`.
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:
...
@@ -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
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
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
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)
.. 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:
...
@@ -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
Returning a true value from this method will cause the :keyword:`with` statement
to suppress the exception and continue execution with the statement immediately
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
propagating after this method has finished executing. Exceptions that occur
during execution of this method will replace any exception that occurred in the
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
The exception passed in should never be reraised explicitly - instead, this
method should return a false value to indicate that the method completed
method should return a false value to indicate that the method completed
...
...
Doc/library/telnetlib.rst
View file @
2b57c43f
...
@@ -44,7 +44,7 @@ Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).
...
@@ -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.
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
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::
:meth:`close` method is called::
>>> from telnetlib import Telnet
>>> from telnetlib import Telnet
...
...
Doc/library/tempfile.rst
View file @
2b57c43f
...
@@ -124,7 +124,7 @@ The module defines the following user-callable items:
...
@@ -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
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
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 :keyword:`with` statement, if there is one.
The directory can be explicitly cleaned up by calling the
The directory can be explicitly cleaned up by calling the
...
...
Doc/library/threading.rst
View file @
2b57c43f
...
@@ -973,8 +973,8 @@ As an example, here is a simple way to synchronize a client and server thread::
...
@@ -973,8 +973,8 @@ As an example, here is a simple way to synchronize a client and server thread::
.. _with-locks:
.. _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
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`
:meth:`release` methods can be used as context managers for a :keyword:`with`
...
...
Doc/library/wave.rst
View file @
2b57c43f
...
@@ -40,7 +40,7 @@ The :mod:`wave` module defines the following function and exception:
...
@@ -40,7 +40,7 @@ The :mod:`wave` module defines the following function and exception:
the file object.
the file object.
The :func:`.open` function may be used in a :keyword:`with` statement. When
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_read.close>` or :meth:`Wave_write.close()
<wave.Wave_write.close()>` method is called.
<wave.Wave_write.close()>` method is called.
...
...
Doc/library/xml.dom.minidom.rst
View file @
2b57c43f
...
@@ -126,7 +126,7 @@ module documentation. This section lists the differences between the API and
...
@@ -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`
You can avoid calling this method explicitly by using the :keyword:`with`
statement. The following code will automatically unlink *dom* when the
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:
with xml.dom.minidom.parse(datasource) as dom:
... # Work with dom.
... # Work with dom.
...
...
Doc/library/zipfile.rst
View file @
2b57c43f
...
@@ -181,7 +181,7 @@ ZipFile Objects
...
@@ -181,7 +181,7 @@ ZipFile Objects
ZipFile is also a context manager and therefore supports the
ZipFile is also a context manager and therefore supports the
:keyword:`with` statement. In the example, *myzip* is closed after 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
:
with
ZipFile
(
'spam.zip'
,
'w'
)
as
myzip
:
myzip
.
write
(
'eggs.txt'
)
myzip
.
write
(
'eggs.txt'
)
...
...
Doc/reference/compound_stmts.rst
View file @
2b57c43f
...
@@ -78,11 +78,11 @@ on a separate line for clarity.
...
@@ -78,11 +78,11 @@ on a separate line for clarity.
.. _elif:
.. _elif:
.. _else:
.. _else:
The :keyword:`if` statement
The :keyword:`
!
if` statement
===========================
===========================
=
.. index::
.. index::
statement: if
!
statement: if
keyword: elif
keyword: elif
keyword: else
keyword: else
single: : (colon); compound statement
single: : (colon); compound statement
...
@@ -103,14 +103,13 @@ false, the suite of the :keyword:`else` clause, if present, is executed.
...
@@ -103,14 +103,13 @@ false, the suite of the :keyword:`else` clause, if present, is executed.
.. _while:
.. _while:
The :keyword:`while` statement
The :keyword:`
!
while` statement
==============================
==============================
=
.. index::
.. index::
statement: while
!
statement: while
keyword: else
keyword: else
pair: loop; statement
pair: loop; statement
keyword: else
single: : (colon); compound statement
single: : (colon); compound statement
The :keyword:`while` statement is used for repeated execution as long as an
The :keyword:`while` statement is used for repeated execution as long as an
...
@@ -122,7 +121,7 @@ expression is true:
...
@@ -122,7 +121,7 @@ expression is true:
This repeatedly tests the expression and, if it is true, executes the first
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; 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.
terminates.
.. index::
.. index::
...
@@ -130,25 +129,22 @@ terminates.
...
@@ -130,25 +129,22 @@ terminates.
statement: continue
statement: continue
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 goes back
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.
to testing the expression.
.. _for:
.. _for:
The :keyword:`for` statement
The :keyword:`
!
for` statement
============================
============================
=
.. index::
.. index::
statement: for
!
statement: for
keyword: in
keyword: in
keyword: else
keyword: else
pair: target; list
pair: target; list
pair: loop; statement
pair: loop; statement
keyword: in
keyword: else
pair: target; list
object: sequence
object: sequence
single: : (colon); compound statement
single: : (colon); compound statement
...
@@ -166,16 +162,16 @@ by the iterator. Each item in turn is assigned to the target list using the
...
@@ -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
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
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::
.. index::
statement: break
statement: break
statement: continue
statement: continue
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 is no next
with the next item, or with the :keyword:`
!
else` clause if there is no next
item.
item.
The for-loop makes assignments to the variables in the target list.
The for-loop makes assignments to the variables in the target list.
...
@@ -224,11 +220,11 @@ returns the list ``[0, 1, 2]``.
...
@@ -224,11 +220,11 @@ returns the list ``[0, 1, 2]``.
.. _except:
.. _except:
.. _finally:
.. _finally:
The :keyword:`try` statement
The :keyword:`
!
try` statement
============================
============================
=
.. index::
.. index::
statement: try
!
statement: try
keyword: except
keyword: except
keyword: finally
keyword: finally
keyword: else
keyword: else
...
@@ -250,7 +246,7 @@ for a group of statements:
...
@@ -250,7 +246,7 @@ for a group of statements:
The :keyword:`except` clause(s) specify one or more exception handlers. When no
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.
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
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
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
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).
...
@@ -270,7 +266,7 @@ as if the entire :keyword:`try` statement raised the exception).
.. index:: single: as; except clause
.. index:: single: as; except clause
When a matching except clause is found, the exception is assigned to the target
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
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
executable block. When the end of this block is reached, execution continues
normally after the entire try statement. (This means that if two nested
normally after the entire try statement. (This means that if two nested
...
@@ -314,22 +310,22 @@ from a function that handled an exception.
...
@@ -314,22 +310,22 @@ from a function that handled an exception.
statement: break
statement: break
statement: continue
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:`try` suite, no exception was raised, and no :keyword:`return`,
:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in
: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.
clauses.
.. index:: keyword: finally
.. index:: keyword: finally
If :keyword:`finally` is present, it specifies a 'cleanup' handler. The
If :keyword:`finally` is present, it specifies a 'cleanup' handler. The
:keyword:`try` clause is executed, including any :keyword:`except` and
:keyword:`try` clause is executed, including any :keyword:`except` and
:keyword:`else` clauses. If an exception occurs in any of the clauses and is
: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
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
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.
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::
or :keyword:`continue` statement, the saved exception is discarded::
>>> def f():
>>> def f():
...
@@ -350,12 +346,12 @@ the :keyword:`finally` clause.
...
@@ -350,12 +346,12 @@ the :keyword:`finally` clause.
statement: continue
statement: continue
When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is
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.'
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`
The return value of a function is determined by the last :keyword:`return`
statement executed. Since the :keyword:`finally` clause always executes, a
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::
always be the last one executed::
>>> def foo():
>>> def foo():
...
@@ -379,11 +375,11 @@ may be found in section :ref:`raise`.
...
@@ -379,11 +375,11 @@ may be found in section :ref:`raise`.
.. _with:
.. _with:
.. _as:
.. _as:
The :keyword:`with` statement
The :keyword:`
!
with` statement
=============================
=============================
=
.. index::
.. index::
statement: with
!
statement: with
keyword: as
keyword: as
single: as; with statement
single: as; with statement
single: , (comma); with statement
single: , (comma); with statement
...
@@ -595,7 +591,7 @@ name), for immediate use in expressions. This uses lambda expressions, describe
...
@@ -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
section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a
simplified function definition; a function defined in a ":keyword:`def`"
simplified function definition; a function defined in a ":keyword:`def`"
statement can be passed around or assigned to another name just like a function
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.
since it allows the execution of multiple statements and annotations.
**Programmer's note:** Functions are first-class objects. A "``def``" statement
**Programmer's note:** Functions are first-class objects. A "``def``" statement
...
@@ -758,8 +754,8 @@ An example of a coroutine function::
...
@@ -758,8 +754,8 @@ An example of a coroutine function::
.. index:: statement: async for
.. index:: statement: async for
.. _`async for`:
.. _`async for`:
The :keyword:`async for` statement
The :keyword:`
!
async for` statement
----------------------------------
----------------------------------
-
.. productionlist::
.. productionlist::
async_for_stmt: "async" `for_stmt`
async_for_stmt: "async" `for_stmt`
...
@@ -802,8 +798,8 @@ body of a coroutine function.
...
@@ -802,8 +798,8 @@ body of a coroutine function.
.. index:: statement: async with
.. index:: statement: async with
.. _`async with`:
.. _`async with`:
The :keyword:`async with` statement
The :keyword:`
!
async with` statement
-----------------------------------
-----------------------------------
-
.. productionlist::
.. productionlist::
async_with_stmt: "async" `with_stmt`
async_with_stmt: "async" `with_stmt`
...
...
Doc/reference/datamodel.rst
View file @
2b57c43f
...
@@ -620,7 +620,7 @@ Callable types
...
@@ -620,7 +620,7 @@ Callable types
called, always returns an iterator object which can be used to execute the
called, always returns an iterator object which can be used to execute the
body of the function: calling the iterator's :meth:`iterator.__next__`
body of the function: calling the iterator's :meth:`iterator.__next__`
method will cause the function to execute until it provides a value
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`
: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
exception is raised and the iterator will have reached the end of the set of
values to be returned.
values to be returned.
...
@@ -700,7 +700,7 @@ Modules
...
@@ -700,7 +700,7 @@ Modules
Modules are a basic organizational unit of Python code, and are created by
Modules are a basic organizational unit of Python code, and are created by
the :ref:`import system <importsystem>` as invoked either by the
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
functions such as :func:`importlib.import_module` and built-in
:func:`__import__`. A module object has a namespace implemented by a
:func:`__import__`. A module object has a namespace implemented by a
dictionary object (this is the dictionary referenced by the ``__globals__``
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
...
@@ -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
established when executing a :keyword:`with` statement. The context manager
handles the entry into, and the exit from, the desired runtime context for the
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
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.
used by directly invoking their methods.
.. index::
.. index::
...
@@ -2440,7 +2440,7 @@ For more information on context managers, see :ref:`typecontextmanager`.
...
@@ -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
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
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)
.. method:: object.__exit__(self, exc_type, exc_value, traceback)
...
...
Doc/reference/executionmodel.rst
View file @
2b57c43f
...
@@ -58,8 +58,8 @@ The following constructs bind names: formal parameters to functions,
...
@@ -58,8 +58,8 @@ The following constructs bind names: formal parameters to functions,
:keyword:`import` statements, class and function definitions (these bind the
:keyword:`import` statements, class and function definitions (these bind the
class or function name in the defining block), and targets that are identifiers
class or function name in the defining block), and targets that are identifiers
if occurring in an assignment, :keyword:`for` loop header, or after
if occurring in an assignment, :keyword:`for` loop header, or after
:keyword:`as` in a :keyword:`with` statement or :keyword:`except` clause.
:keyword:`
!
as` in a :keyword:`with` statement or :keyword:`except` clause.
The :keyword:`import` statement
The :keyword:`
!
import` statement
of the form ``from ... import *`` binds all names defined in the imported
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
module, except those beginning with an underscore. This form may only be used
at the module level.
at the module level.
...
@@ -123,7 +123,7 @@ namespace. Names are resolved in the top-level namespace by searching the
...
@@ -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,
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
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
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.
all uses of the name.
The :keyword:`global` statement has the same scope as a name binding operation
The :keyword:`global` statement has the same scope as a name binding operation
...
...
Doc/reference/expressions.rst
View file @
2b57c43f
...
@@ -185,20 +185,20 @@ Common syntax elements for comprehensions are:
...
@@ -185,20 +185,20 @@ Common syntax elements for comprehensions are:
comp_if: "if" `expression_nocond` [`comp_iter`]
comp_if: "if" `expression_nocond` [`comp_iter`]
The comprehension consists of a single expression followed by at least one
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
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
nesting from left to right, and evaluating the expression to produce an element
each time the innermost block is reached.
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
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.
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
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
nested scope. Subsequent :keyword:`
!
for` clauses and any filter condition in the
leftmost :keyword:`for` clause cannot be evaluated in the enclosing scope as
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:
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)]``.
``[x*y for x in range(10) for y in range(x, x+10)]``.
...
@@ -209,14 +209,14 @@ nested scope.
...
@@ -209,14 +209,14 @@ nested scope.
.. index::
.. index::
single: await; in comprehensions
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`.
clause may be used to iterate over a :term:`asynchronous iterator`.
A comprehension in an :keyword:`async def` function may consist of either a
A comprehension in an :keyword:`
!
async def` function may consist of either a
:keyword:`
for` or :keyword:`
async for` clause following the leading
:keyword:`
!for` or :keyword:`!
async for` clause following the leading
expression, may contain additional :keyword:`
for` or :keyword:`
async for`
expression, may contain additional :keyword:`
!for` or :keyword:`!
async for`
clauses, and may also use :keyword:`await` expressions.
clauses, and may also use :keyword:`await` expressions.
If a comprehension contains either :keyword:`async for` clauses
If a comprehension contains either :keyword:`
!
async for` clauses
or :keyword:`await` expressions it is called an
or :keyword:`
!
await` expressions it is called an
:dfn:`asynchronous comprehension`. An asynchronous comprehension may
:dfn:`asynchronous comprehension`. An asynchronous comprehension may
suspend the execution of the coroutine function in which it appears.
suspend the execution of the coroutine function in which it appears.
See also :pep:`530`.
See also :pep:`530`.
...
@@ -360,11 +360,11 @@ brackets or curly braces.
...
@@ -360,11 +360,11 @@ brackets or curly braces.
Variables used in the generator expression are evaluated lazily when the
Variables used in the generator expression are evaluated lazily when the
:meth:`~generator.__next__` method is called for the generator object (in the same
:meth:`~generator.__next__` method is called for the generator object (in the same
fashion as normal generators). However, the iterable expression in the
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
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.
is defined, rather than at the point where the first value is retrieved.
Subsequent :keyword:`for` clauses and any filter condition in the leftmost
Subsequent :keyword:`
!
for` clauses and any filter condition in the leftmost
:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
:keyword:`
!
for` clause cannot be evaluated in the enclosing scope as they may
depend on the values obtained from the leftmost iterable. For example:
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))``.
``(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
...
@@ -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
itself, ``yield`` and ``yield from`` expressions are prohibited in the
implicitly defined generator.
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
clauses or :keyword:`await` expressions it is called an
:dfn:`asynchronous generator expression`. An asynchronous generator
:dfn:`asynchronous generator expression`. An asynchronous generator
expression returns a new asynchronous generator object,
expression returns a new asynchronous generator object,
...
@@ -637,12 +637,12 @@ that method.
...
@@ -637,12 +637,12 @@ that method.
In an asynchronous generator function, yield expressions are allowed anywhere
In an asynchronous generator function, yield expressions are allowed anywhere
in a :keyword:`try` construct. However, if an asynchronous generator is not
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
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`
construct could result in a failure to execute pending :keyword:`finally`
clauses. In this case, it is the responsibility of the event loop or
clauses. In this case, it is the responsibility of the event loop or
scheduler running the asynchronous generator to call the asynchronous
scheduler running the asynchronous generator to call the asynchronous
generator-iterator's :meth:`~agen.aclose` method and run the resulting
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 execute.
To take care of finalization, an event loop should define
To take care of finalization, an event loop should define
...
@@ -1548,7 +1548,7 @@ Membership test operations
...
@@ -1548,7 +1548,7 @@ Membership test operations
The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
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.
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
``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,
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
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)``.
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
...
@@ -1648,6 +1648,8 @@ returns a boolean value regardless of the type of its argument
(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
.. _if_expr:
Conditional expressions
Conditional expressions
=======================
=======================
...
@@ -1790,7 +1792,7 @@ precedence and have a left-to-right chaining feature as described in the
...
@@ -1790,7 +1792,7 @@ precedence and have a left-to-right chaining feature as described in the
+===============================================+=====================================+
+===============================================+=====================================+
| :keyword:`lambda` | Lambda expression |
| :keyword:`lambda` | Lambda expression |
+-----------------------------------------------+-------------------------------------+
+-----------------------------------------------+-------------------------------------+
| :keyword:`if
` -- :keyword:`else`
| Conditional expression |
| :keyword:`if
<if_expr>` -- :keyword:`!else`
| Conditional expression |
+-----------------------------------------------+-------------------------------------+
+-----------------------------------------------+-------------------------------------+
| :keyword:`or` | Boolean OR |
| :keyword:`or` | Boolean OR |
+-----------------------------------------------+-------------------------------------+
+-----------------------------------------------+-------------------------------------+
...
...
Doc/reference/import.rst
View file @
2b57c43f
...
@@ -15,11 +15,11 @@ way. Functions such as :func:`importlib.import_module` and built-in
...
@@ -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
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
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
.
a
call
to
the
:
func
:`
__import__
`
function
,
with
the
appropriate
arguments
.
The
return
value
of
:
func
:`
__import__
`
is
used
to
perform
the
name
The
return
value
of
:
func
:`
__import__
`
is
used
to
perform
the
name
binding
operation
of
the
:
keyword
:`
import
`
statement
.
See
the
binding
operation
of
the
:
keyword
:`
!
import` statement. See the
:
keyword
:`
import
`
statement
for
the
exact
details
of
that
name
binding
:
keyword
:`
!
import` statement for the exact details of that name binding
operation
.
operation
.
A
direct
call
to
:
func
:`
__import__
`
performs
only
the
module
search
and
,
if
A
direct
call
to
:
func
:`
__import__
`
performs
only
the
module
search
and
,
if
...
...
Doc/reference/simple_stmts.rst
View file @
2b57c43f
...
@@ -369,11 +369,11 @@ target, then the interpreter evaluates the target except for the last
...
@@ -369,11 +369,11 @@ target, then the interpreter evaluates the target except for the last
..
_assert
:
..
_assert
:
The
:
keyword
:`
assert
`
statement
The
:
keyword
:`
!
assert` statement
===============================
===============================
=
..
index
::
..
index
::
statement
:
assert
!
statement: assert
pair
:
debugging
;
assertions
pair
:
debugging
;
assertions
single
:
,
(
comma
);
expression
list
single
:
,
(
comma
);
expression
list
...
@@ -412,8 +412,8 @@ is determined when the interpreter starts.
...
@@ -412,8 +412,8 @@ is determined when the interpreter starts.
..
_pass
:
..
_pass
:
The
:
keyword
:`
pass
`
statement
The
:
keyword
:`
!
pass` statement
=============================
=============================
=
..
index
::
..
index
::
statement
:
pass
statement
:
pass
...
@@ -434,11 +434,11 @@ code needs to be executed, for example::
...
@@ -434,11 +434,11 @@ code needs to be executed, for example::
..
_del
:
..
_del
:
The
:
keyword
:`
del
`
statement
The
:
keyword
:`
!
del` statement
============================
============================
=
..
index
::
..
index
::
statement
:
del
!
statement: del
pair
:
deletion
;
target
pair
:
deletion
;
target
triple
:
deletion
;
target
;
list
triple
:
deletion
;
target
;
list
...
@@ -473,11 +473,11 @@ the sliced object).
...
@@ -473,11 +473,11 @@ the sliced object).
..
_return
:
..
_return
:
The
:
keyword
:`
return
`
statement
The
:
keyword
:`
!
return` statement
===============================
===============================
=
..
index
::
..
index
::
statement
:
return
!
statement: return
pair
:
function
;
definition
pair
:
function
;
definition
pair
:
class
;
definition
pair
:
class
;
definition
...
@@ -495,7 +495,7 @@ If an expression list is present, it is evaluated, else ``None`` is substituted.
...
@@ -495,7 +495,7 @@ If an expression list is present, it is evaluated, else ``None`` is substituted.
..
index
::
keyword
:
finally
..
index
::
keyword
:
finally
When
:
keyword
:`
return
`
passes
control
out
of
a
:
keyword
:`
try
`
statement
with
a
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
.
really
leaving
the
function
.
In
a
generator
function
,
the
:
keyword
:`
return
`
statement
indicates
that
the
In
a
generator
function
,
the
:
keyword
:`
return
`
statement
indicates
that
the
...
@@ -505,13 +505,13 @@ becomes the :attr:`StopIteration.value` attribute.
...
@@ -505,13 +505,13 @@ becomes the :attr:`StopIteration.value` attribute.
In
an
asynchronous
generator
function
,
an
empty
:
keyword
:`
return
`
statement
In
an
asynchronous
generator
function
,
an
empty
:
keyword
:`
return
`
statement
indicates
that
the
asynchronous
generator
is
done
and
will
cause
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
.
statement
is
a
syntax
error
in
an
asynchronous
generator
function
.
..
_yield
:
..
_yield
:
The
:
keyword
:`
yield
`
statement
The
:
keyword
:`
!
yield` statement
==============================
==============================
=
..
index
::
..
index
::
statement
:
yield
statement
:
yield
...
@@ -546,11 +546,11 @@ For full details of :keyword:`yield` semantics, refer to the
...
@@ -546,11 +546,11 @@ For full details of :keyword:`yield` semantics, refer to the
..
_raise
:
..
_raise
:
The
:
keyword
:`
raise
`
statement
The
:
keyword
:`
!
raise` statement
==============================
==============================
=
..
index
::
..
index
::
statement
:
raise
!
statement: raise
single
:
exception
single
:
exception
pair
:
raising
;
exception
pair
:
raising
;
exception
single
:
__traceback__
(
exception
attribute
)
single
:
__traceback__
(
exception
attribute
)
...
@@ -649,11 +649,11 @@ and information about handling exceptions is in section :ref:`try`.
...
@@ -649,11 +649,11 @@ and information about handling exceptions is in section :ref:`try`.
..
_break
:
..
_break
:
The
:
keyword
:`
break
`
statement
The
:
keyword
:`
!
break` statement
==============================
==============================
=
..
index
::
..
index
::
statement
:
break
!
statement: break
statement
:
for
statement
:
for
statement
:
while
statement
:
while
pair
:
loop
;
statement
pair
:
loop
;
statement
...
@@ -668,7 +668,7 @@ that loop.
...
@@ -668,7 +668,7 @@ that loop.
..
index
::
keyword
:
else
..
index
::
keyword
:
else
pair
:
loop
control
;
target
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
.
clause
if
the
loop
has
one
.
If
a
:
keyword
:`
for
`
loop
is
terminated
by
:
keyword
:`
break
`,
the
loop
control
If
a
:
keyword
:`
for
`
loop
is
terminated
by
:
keyword
:`
break
`,
the
loop
control
...
@@ -677,17 +677,17 @@ target keeps its current value.
...
@@ -677,17 +677,17 @@ target keeps its current value.
..
index
::
keyword
:
finally
..
index
::
keyword
:
finally
When
:
keyword
:`
break
`
passes
control
out
of
a
:
keyword
:`
try
`
statement
with
a
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
.
really
leaving
the
loop
.
..
_continue
:
..
_continue
:
The
:
keyword
:`
continue
`
statement
The
:
keyword
:`
!
continue` statement
=================================
=================================
=
..
index
::
..
index
::
statement
:
continue
!
statement: continue
statement
:
for
statement
:
for
statement
:
while
statement
:
while
pair
:
loop
;
statement
pair
:
loop
;
statement
...
@@ -701,18 +701,18 @@ The :keyword:`continue` statement
...
@@ -701,18 +701,18 @@ The :keyword:`continue` statement
that
loop
.
It
continues
with
the
next
cycle
of
the
nearest
enclosing
loop
.
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
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
.
really
starting
the
next
loop
cycle
.
..
_import
:
..
_import
:
..
_from
:
..
_from
:
The
:
keyword
:`
import
`
statement
The
:
keyword
:`
!
import` statement
===============================
===============================
=
..
index
::
..
index
::
statement
:
import
!
statement: import
single
:
module
;
importing
single
:
module
;
importing
pair
:
name
;
binding
pair
:
name
;
binding
keyword
:
from
keyword
:
from
...
@@ -755,8 +755,8 @@ available in the local namespace in one of three ways:
...
@@ -755,8 +755,8 @@ available in the local namespace in one of three ways:
.. index:: single: as; import statement
.. index:: single: as; import statement
* If the module name is followed by :keyword:`as`, then the name
* If the module name is followed by :keyword:`
!
as`, then the name
following :keyword:`as` is bound directly to the imported module.
following :keyword:`
!
as` is bound directly to the imported module.
* If no other name is specified, and the module being imported is a top
* 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
level module, the module'
s
name
is
bound
in
the
local
namespace
as
a
reference
to
the
imported
module
reference
to
the
imported
module
...
@@ -781,7 +781,7 @@ The :keyword:`from` form uses a slightly more complex process:
...
@@ -781,7 +781,7 @@ The :keyword:`from` form uses a slightly more complex process:
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
stored
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
Examples
::
Examples
::
...
@@ -922,11 +922,11 @@ after the script is executed.
...
@@ -922,11 +922,11 @@ after the script is executed.
.. _global:
.. _global:
The :keyword:`global` statement
The :keyword:`
!
global` statement
===============================
===============================
=
.. index::
.. index::
statement: global
!
statement: global
triple: global; name; binding
triple: global; name; binding
single: , (comma); identifier list
single: , (comma); identifier list
...
@@ -936,11 +936,11 @@ The :keyword:`global` statement
...
@@ -936,11 +936,11 @@ The :keyword:`global` statement
The :keyword:`global` statement is a declaration which holds for the entire
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
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
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.
declared global.
Names listed in a :keyword:`global` statement must not be used in the same code
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
Names listed in a :keyword:`global` statement must not be defined as formal
parameters or in a :keyword:`for` loop control target, :keyword:`class`
parameters or in a :keyword:`for` loop control target, :keyword:`class`
...
@@ -959,18 +959,18 @@ annotation.
...
@@ -959,18 +959,18 @@ annotation.
builtin: compile
builtin: compile
**Programmer'
s
note
:**
:
keyword
:`
global
`
is
a
directive
to
the
parser
.
It
**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
.
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
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
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
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
.
call
.
The
same
applies
to
the
:
func
:`
eval
`
and
:
func
:`
compile
`
functions
.
..
_nonlocal
:
..
_nonlocal
:
The
:
keyword
:`
nonlocal
`
statement
The
:
keyword
:`
!
nonlocal` statement
=================================
=================================
=
..
index
::
statement
:
nonlocal
..
index
::
statement
:
nonlocal
single
:
,
(
comma
);
identifier
list
single
:
,
(
comma
);
identifier
list
...
...
Doc/tutorial/classes.rst
View file @
2b57c43f
...
@@ -783,7 +783,7 @@ calls :func:`iter` on the container object. The function returns an iterator
...
@@ -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
object that defines the method :meth:`~iterator.__next__` which accesses
elements in the container one at a time. When there are no more elements,
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
: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::
using the :func:`next` built-in function; this example shows how it all works::
>>> s = 'abc'
>>> s = 'abc'
...
...
Doc/tutorial/controlflow.rst
View file @
2b57c43f
...
@@ -10,8 +10,8 @@ control flow statements known from other languages, with some twists.
...
@@ -10,8 +10,8 @@ control flow statements known from other languages, with some twists.
.. _tut-if:
.. _tut-if:
:keyword:`if` Statements
:keyword:`
!
if` Statements
========================
========================
=
Perhaps the most well-known statement type is the :keyword:`if` statement. For
Perhaps the most well-known statement type is the :keyword:`if` statement. For
example::
example::
...
@@ -31,16 +31,16 @@ example::
...
@@ -31,16 +31,16 @@ example::
More
More
There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
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
optional. The keyword ':keyword:`
!
elif`' is short for 'else if', and is useful
to avoid excessive indentation. An :keyword:`
if` ... :keyword:`
elif` ...
to avoid excessive indentation. An :keyword:`
!if` ... :keyword:`!
elif` ...
:keyword:`elif` ... sequence is a substitute for the ``switch`` or
:keyword:`
!
elif` ... sequence is a substitute for the ``switch`` or
``case`` statements found in other languages.
``case`` statements found in other languages.
.. _tut-for:
.. _tut-for:
:keyword:`for` Statements
:keyword:`
!
for` Statements
=========================
=========================
=
.. index::
.. index::
statement: for
statement: for
...
@@ -48,7 +48,7 @@ to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
...
@@ -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
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
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
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
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):
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
...
@@ -154,13 +154,13 @@ Later we will see more functions that return iterables and take iterables as arg
.. _tut-break:
.. _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
The :keyword:`break` statement, like in C, breaks out of the innermost enclosing
:keyword:`for` or :keyword:`while` loop.
: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
terminates through exhaustion of the list (with :keyword:`for`) or when the
condition becomes false (with :keyword:`while`), but not when the loop is
condition becomes false (with :keyword:`while`), but not when the loop is
terminated by a :keyword:`break` statement. This is exemplified by the
terminated by a :keyword:`break` statement. This is exemplified by the
...
@@ -189,9 +189,9 @@ the :keyword:`for` loop, **not** the :keyword:`if` statement.)
...
@@ -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
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
``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``
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`.
:ref:`tut-handling`.
The :keyword:`continue` statement, also borrowed from C, continues with the next
The :keyword:`continue` statement, also borrowed from C, continues with the next
...
@@ -213,8 +213,8 @@ iteration of the loop::
...
@@ -213,8 +213,8 @@ iteration of the loop::
.. _tut-pass:
.. _tut-pass:
:keyword:`pass` Statements
:keyword:`
!
pass` Statements
==========================
==========================
=
The :keyword:`pass` statement does nothing. It can be used when a statement is
The :keyword:`pass` statement does nothing. It can be used when a statement is
required syntactically but the program requires no action. For example::
required syntactically but the program requires no action. For example::
...
@@ -231,7 +231,7 @@ This is commonly used for creating minimal classes::
...
@@ -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
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
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):
>>> def initlog(*args):
... pass # Remember to implement this!
... pass # Remember to implement this!
...
@@ -331,7 +331,7 @@ Fibonacci series, instead of printing it::
...
@@ -331,7 +331,7 @@ Fibonacci series, instead of printing it::
This example, as usual, demonstrates some new Python features:
This example, as usual, demonstrates some new Python features:
* The :keyword:`return` statement returns with a value from a function.
* 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 end of a function also returns ``None``.
* The statement ``result.append(a)`` calls a *method* of the list object
* The statement ``result.append(a)`` calls a *method* of the list object
...
...
Doc/tutorial/datastructures.rst
View file @
2b57c43f
...
@@ -216,9 +216,9 @@ or, equivalently::
...
@@ -216,9 +216,9 @@ or, equivalently::
which is more concise and readable.
which is more concise and readable.
A list comprehension consists of brackets containing an expression followed
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
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
For example, this listcomp combines the elements of two lists if they are not
equal::
equal::
...
@@ -330,12 +330,12 @@ See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
...
@@ -330,12 +330,12 @@ See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
.. _tut-del:
.. _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
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
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
slices from a list or clear the entire list (which we did earlier by assignment
of an empty list to the slice). For example::
of an empty list to the slice). For example::
...
...
Doc/tutorial/errors.rst
View file @
2b57c43f
...
@@ -114,7 +114,7 @@ The :keyword:`try` statement works as follows.
...
@@ -114,7 +114,7 @@ The :keyword:`try` statement works as follows.
A :keyword:`try` statement may have more than one except clause, to specify
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 for different exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
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::
name multiple exceptions as a parenthesized tuple, for example::
... except (RuntimeError, TypeError, NameError):
... except (RuntimeError, TypeError, NameError):
...
@@ -180,10 +180,10 @@ example::
...
@@ -180,10 +180,10 @@ example::
print(arg, 'has', len(f.readlines()), 'lines')
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
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
the :keyword:`try` clause because it avoids accidentally catching an exception
that wasn't raised by the code being protected by the :keyword:`try` ...
that wasn't raised by the code being protected by the :keyword:`
!
try` ...
:keyword:`except` statement.
:keyword:`
!
except` statement.
When an exception occurs, it may have an associated value, also known as the
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
exception's *argument*. The presence and type of the argument depend on the
...
@@ -343,11 +343,11 @@ example::
...
@@ -343,11 +343,11 @@ example::
A *finally clause* is always executed before leaving the :keyword:`try`
A *finally clause* is always executed before leaving the :keyword:`try`
statement, whether an exception has occurred or not. When an exception has
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
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:`except` clause (or it has occurred in an :keyword:`
!
except` or
:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
: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"
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
when any other clause of the :keyword:`
!
try` statement is left via a
:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
complicated example::
complicated example::
...
@@ -376,7 +376,7 @@ complicated example::
...
@@ -376,7 +376,7 @@ complicated example::
As you can see, the :keyword:`finally` clause is executed in any event. The
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
: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.
clause has been executed.
In real world applications, the :keyword:`finally` clause is useful for
In real world applications, the :keyword:`finally` clause is useful for
...
...
Doc/tutorial/inputoutput.rst
View file @
2b57c43f
...
@@ -317,7 +317,7 @@ reading and writing such files.
...
@@ -317,7 +317,7 @@ reading and writing such files.
It is good practice to use the :keyword:`with` keyword when dealing
It is good practice to use the :keyword:`with` keyword when dealing
with file objects. The advantage is that the file is properly closed
with file objects. The advantage is that the file is properly closed
after its suite finishes, even if an exception is raised at some
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::
equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
>>> with open('workfile') as f:
>>> with open('workfile') as f:
...
...
Doc/tutorial/modules.rst
View file @
2b57c43f
...
@@ -112,8 +112,8 @@ Note that in general the practice of importing ``*`` from a module or package is
...
@@ -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
frowned
upon
,
since
it
often
causes
poorly
readable
code
.
However
,
it
is
okay
to
use
it
to
save
typing
in
interactive
sessions
.
use
it
to
save
typing
in
interactive
sessions
.
If
the
module
name
is
followed
by
:
keyword
:`
as
`,
then
the
name
If
the
module
name
is
followed
by
:
keyword
:`
!
as`, then the name
following
:
keyword
:`
as
`
is
bound
directly
to
the
imported
module
.
following
:
keyword
:`
!
as` is bound directly to the imported module.
::
::
...
...
Doc/whatsnew/2.0.rst
View file @
2b57c43f
...
@@ -284,7 +284,7 @@ write the following to do it::
...
@@ -284,7 +284,7 @@ write the following to do it::
L)
L)
Because of Python's scoping rules, a default argument is used so that the
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::
substring is being searched for. List comprehensions make this cleaner::
sublist = [ s for s in L if string.find(s, S) != -1 ]
sublist = [ s for s in L if string.find(s, S) != -1 ]
...
@@ -296,11 +296,11 @@ List comprehensions have the form::
...
@@ -296,11 +296,11 @@ List comprehensions have the form::
for exprN in sequenceN
for exprN in sequenceN
if condition ]
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
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
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
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
is optional; if present, *expression* is only evaluated and added to the result
if *condition* is true.
if *condition* is true.
...
@@ -316,7 +316,7 @@ following Python code::
...
@@ -316,7 +316,7 @@ following Python code::
# the expression to the
# the expression to the
# resulting list.
# 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
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
the sequences. If you have two lists of length 3, the output list is 9 elements
long::
long::
...
@@ -541,8 +541,8 @@ true if *obj* is present in the sequence *seq*; Python computes this by simply
...
@@ -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
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
:exc:`IndexError` is encountered. Moshe Zadka contributed a patch which adds a
:meth:`__contains__` magic method for providing a custom implementation for
: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`. 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` means for them via a new slot in the sequence protocol.
Earlier versions of Python used a recursive algorithm for deleting objects.
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
Deeply nested data structures could cause the interpreter to fill up the C stack
...
...
Doc/whatsnew/2.1.rst
View file @
2b57c43f
...
@@ -52,7 +52,7 @@ The function :func:`g` will always raise a :exc:`NameError` exception, because
...
@@ -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
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
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
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
In
code
which
uses
:
keyword
:`
lambda
`
you
can
often
find
local
variables
being
copied
by
passing
them
as
the
default
values
of
arguments
.
::
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
...
@@ -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
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
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
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
the
Python
bytecode
compiler
parses
code
and
generates
bytecode
,
so
they
must
precede
any
statement
that
will
result
in
bytecodes
being
produced
.
precede
any
statement
that
will
result
in
bytecodes
being
produced
.
...
...
Doc/whatsnew/2.2.rst
View file @
2b57c43f
...
@@ -121,7 +121,7 @@ added so if no built-in type is suitable, you can just subclass
...
@@ -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
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
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`
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
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`,
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::
...
@@ -560,7 +560,7 @@ Here's the simplest example of a generator function::
yield i
yield i
A new keyword, :keyword:`yield`, was introduced for generators. Any function
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
detected by Python's bytecode compiler which compiles the function specially as
a result. Because a new keyword was introduced, generators must be explicitly
a result. Because a new keyword was introduced, generators must be explicitly
enabled in a module by including a ``from __future__ import generators``
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
...
@@ -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
returns a generator object that supports the iterator protocol. On executing
the :keyword:`yield` statement, the generator outputs the value of ``i``,
the :keyword:`yield` statement, the generator outputs the value of ``i``,
similar to a :keyword:`return` statement. The big difference between
similar to a :keyword:`return` statement. The big difference between
:keyword:`
yield` and a :keyword:`
return` statement is that on reaching a
: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` the generator's state of execution is suspended and local
variables are preserved. On the next call to the generator's ``next()`` method,
variables are preserved. On the next call to the generator's ``next()`` method,
the function will resume executing immediately after the :keyword:`yield`
the function will resume executing immediately after the :keyword:`
!
yield`
statement. (For complicated reasons, the :keyword:`yield` statement isn't
statement. (For complicated reasons, the :keyword:`
!
yield` statement isn't
allowed inside the :keyword:`try` block of a
allowed inside the :keyword:`
!
try` block of a
:keyword:`try`...\ :keyword:`finally` statement; read :pep:`255` for a full
: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::
Here's a sample usage of the :func:`generate_ints` generator::
...
@@ -602,7 +602,7 @@ generate_ints(3)``.
...
@@ -602,7 +602,7 @@ generate_ints(3)``.
Inside a generator function, the :keyword:`return` statement can only be used
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
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
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`
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
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
...
@@ -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
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
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
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
In code which uses :keyword:`
!
lambda` you can often find local variables being
copied by passing them as the default values of arguments. ::
copied by passing them as the default values of arguments. ::
def find(self, name):
def find(self, name):
...
...
Doc/whatsnew/2.3.rst
View file @
2b57c43f
...
@@ -149,7 +149,7 @@ Here's the simplest example of a generator function::
...
@@ -149,7 +149,7 @@ Here's the simplest example of a generator function::
yield i
yield i
A new keyword, :keyword:`yield`, was introduced for generators. Any function
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
detected by Python's bytecode compiler which compiles the function specially as
a result.
a result.
...
@@ -157,14 +157,14 @@ When you call a generator function, it doesn't return a single value; instead it
...
@@ -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
returns a generator object that supports the iterator protocol. On executing
the :keyword:`yield` statement, the generator outputs the value of ``i``,
the :keyword:`yield` statement, the generator outputs the value of ``i``,
similar to a :keyword:`return` statement. The big difference between
similar to a :keyword:`return` statement. The big difference between
:keyword:`
yield` and a :keyword:`
return` statement is that on reaching a
: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` the generator's state of execution is suspended and local
variables are preserved. On the next call to the generator's ``.next()``
variables are preserved. On the next call to the generator's ``.next()``
method, the function will resume executing immediately after the
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
statement isn't allowed inside the :keyword:`try` block of a
:keyword:`
try`...\ :keyword:`
finally` statement; read :pep:`255` for a full
: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::
Here's a sample usage of the :func:`generate_ints` generator::
...
@@ -188,7 +188,7 @@ generate_ints(3)``.
...
@@ -188,7 +188,7 @@ generate_ints(3)``.
Inside a generator function, the :keyword:`return` statement can only be used
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
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
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`
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
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
...
@@ -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
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
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
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
some random object. The Boolean type is a subclass of the :class:`int` class so
that arithmetic using a Boolean still works. ::
that arithmetic using a Boolean still works. ::
...
...
Doc/whatsnew/2.5.rst
View file @
2b57c43f
...
@@ -370,7 +370,7 @@ PEP 341: Unified try/except/finally
...
@@ -370,7 +370,7 @@ PEP 341: Unified try/except/finally
Until Python 2.5, the :keyword:`try` statement came in two flavours. You could
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
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
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
generating the right bytecode for the combined version was complicated and it
wasn't clear what the semantics of the combined statement should be.
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
...
@@ -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
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
returns the provided value and suspends the function's execution, preserving the
local variables. Execution resumes on the following call to the iterator's
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
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::
assigned to a variable or otherwise operated on::
val = (yield i)
val = (yield i)
...
@@ -458,7 +458,7 @@ expression on the right-hand side of an assignment. This means you can write
...
@@ -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
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
generator's code is then resumed and the :keyword:`yield` expression returns the
specified *value*. If the regular :meth:`next` method is called, 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
Here's the previous example, modified to allow changing the value of the
internal counter. ::
internal counter. ::
...
@@ -644,7 +644,7 @@ Writing Context Managers
...
@@ -644,7 +644,7 @@ Writing Context Managers
------------------------
------------------------
Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
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
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
you like. Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.
underlying implementation and should keep reading.
...
@@ -750,9 +750,9 @@ generator function instead of defining a new class. The generator should yield
...
@@ -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
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
: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
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
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
Our database example from the previous section could be written using this
decorator as::
decorator as::
...
@@ -776,7 +776,7 @@ decorator as::
...
@@ -776,7 +776,7 @@ decorator as::
The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function
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
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::
statement both starts a database transaction and acquires a thread lock::
lock = threading.Lock()
lock = threading.Lock()
...
...
Doc/whatsnew/2.6.rst
View file @
2b57c43f
...
@@ -250,10 +250,10 @@ PEP 343: The 'with' statement
...
@@ -250,10 +250,10 @@ PEP 343: The 'with' statement
The
previous
version
,
Python
2.5
,
added
the
':keyword:`with`'
The
previous
version
,
Python
2.5
,
added
the
':keyword:`with`'
statement
as
an
optional
feature
,
to
be
enabled
by
a
``
from
__future__
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
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
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
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
.
from
Python
2.5
,
you
can
skip
this
section
.
The
':keyword:`with`'
statement
clarifies
code
that
previously
would
use
The
':keyword:`with`'
statement
clarifies
code
that
previously
would
use
...
@@ -331,7 +331,7 @@ Writing Context Managers
...
@@ -331,7 +331,7 @@ Writing Context Managers
------------------------
------------------------
Under the hood, the '
:
keyword
:`
with
`
' statement is fairly complicated. Most
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
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
you like. Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.
underlying implementation and should keep reading.
...
@@ -438,9 +438,9 @@ generator function instead of defining a new class. The generator should yield
...
@@ -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
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
:
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
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
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
Using
this
decorator
,
our
database
example
from
the
previous
section
could
be
written
as
::
could
be
written
as
::
...
@@ -464,7 +464,7 @@ could be written as::
...
@@ -464,7 +464,7 @@ could be written as::
The
:
mod
:`
contextlib
`
module
also
has
a
``
nested
(
mgr1
,
mgr2
,
...)``
function
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
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
::
statement
both
starts
a
database
transaction
and
acquires
a
thread
lock
::
lock
=
threading
.
Lock
()
lock
=
threading
.
Lock
()
...
@@ -1684,7 +1684,7 @@ Some smaller changes made to the core Python language are:
...
@@ -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
* An obscure change: when you use the :func:`locals` function inside a
:keyword:`class` statement, the resulting dictionary no longer returns free
:keyword:`class` statement, the resulting dictionary no longer returns free
variables. (Free variables, in this case, are variables referenced in the
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
.)
..
======================================================================
..
======================================================================
...
...
Doc/whatsnew/2.7.rst
View file @
2b57c43f
...
@@ -708,7 +708,7 @@ Some smaller changes made to the core Python language are:
...
@@ -708,7 +708,7 @@ Some smaller changes made to the core Python language are:
* The :keyword:`with` statement can now use multiple context managers
* The :keyword:`with` statement can now use multiple context managers
in one statement. Context managers are processed from left to right
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::
This means that::
with A() as a, B() as b:
with A() as a, B() as b:
...
@@ -844,7 +844,7 @@ Some smaller changes made to the core Python language are:
...
@@ -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
* The :keyword:`import` statement will no longer try an absolute import
if a relative import (e.g. ``from .os import sep``) fails. This
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;
statements that were only working by accident. (Fixed by Meador Inge;
:issue:`7902`.)
:issue:`7902`.)
...
@@ -1158,7 +1158,7 @@ changes, or look through the Subversion logs for all the details.
...
@@ -1158,7 +1158,7 @@ changes, or look through the Subversion logs for all the details.
* Deprecated function: :func:`contextlib.nested`, which allows
* Deprecated function: :func:`contextlib.nested`, which allows
handling more than one context manager with a single :keyword:`with`
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.
now supports multiple context managers.
* The :mod:`cookielib` module now ignores cookies that have an invalid
* The :mod:`cookielib` module now ignores cookies that have an invalid
...
...
Doc/whatsnew/3.0.rst
View file @
2b57c43f
...
@@ -373,7 +373,7 @@ New Syntax
...
@@ -373,7 +373,7 @@ New Syntax
* :pep:`3104`: :keyword:`nonlocal` statement. Using ``nonlocal x``
* :pep:`3104`: :keyword:`nonlocal` statement. Using ``nonlocal x``
you can now assign directly to a variable in an outer (but
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
* :pep:`3132`: Extended Iterable Unpacking. You can now write things
like ``a, b, *rest = some_sequence``. And even ``*rest, a =
like ``a, b, *rest = some_sequence``. And even ``*rest, a =
...
@@ -408,14 +408,14 @@ Changed Syntax
...
@@ -408,14 +408,14 @@ Changed Syntax
* :pep:`3109` and :pep:`3134`: new :keyword:`raise` statement syntax:
* :pep:`3109` and :pep:`3134`: new :keyword:`raise` statement syntax:
:samp:`raise [{expr} [from {expr}]]`. See below.
: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.)
2.6, actually.)
* ``True``, ``False``, and ``None`` are reserved words. (2.6 partially enforced
* ``True``, ``False``, and ``None`` are reserved words. (2.6 partially enforced
the restrictions on ``None`` already.)
the restrictions on ``None`` already.)
* Change from :keyword:`except` *exc*, *var* to
* 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::
* :pep:`3115`: New Metaclass Syntax. Instead of::
...
@@ -507,9 +507,9 @@ consulted for longer descriptions.
...
@@ -507,9 +507,9 @@ consulted for longer descriptions.
* :ref:`pep-3105`. This is now a standard feature and no longer needs
* :ref:`pep-3105`. This is now a standard feature and no longer needs
to be imported from :mod:`__future__`. More details were given above.
to be imported from :mod:`__future__`. More details were given above.
* :ref:`pep-3110`. The :keyword:`except` *exc* :keyword:`as` *var*
* :ref:`pep-3110`. The :keyword:`except` *exc* :keyword:`
!
as` *var*
syntax is now standard and :keyword:`except` *exc*, *var* is no
syntax is now standard and :keyword:`
!
except` *exc*, *var* is no
longer supported. (Of course, the :keyword:`as` *var* part is still
longer supported. (Of course, the :keyword:`
!
as` *var* part is still
optional.)
optional.)
* :ref:`pep-3112`. The ``b"..."`` string literal notation (and its
* :ref:`pep-3112`. The ``b"..."`` string literal notation (and its
...
...
Doc/whatsnew/3.4.rst
View file @
2b57c43f
...
@@ -1352,7 +1352,7 @@ shelve
...
@@ -1352,7 +1352,7 @@ shelve
------
------
:class:`~shelve.Shelf` instances may now be used in :keyword:`with` statements,
: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`.)
(Contributed by Filip Gruszczyński in :issue:`13896`.)
...
...
Doc/whatsnew/3.7.rst
View file @
2b57c43f
...
@@ -1896,7 +1896,7 @@ Deprecated Python Behavior
...
@@ -1896,7 +1896,7 @@ Deprecated Python Behavior
Yield expressions (both ``yield`` and ``yield from`` clauses) are now deprecated
Yield expressions (both ``yield`` and ``yield from`` clauses) are now deprecated
in comprehensions and generator expressions (aside from the iterable expression
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
always immediately return a container of the appropriate type (rather than
potentially returning a :term:`generator iterator` object), while generator
potentially returning a :term:`generator iterator` object), while generator
expressions won't attempt to interleave their implicit output with the output
expressions won't attempt to interleave their implicit output with the output
...
...
Doc/whatsnew/3.8.rst
View file @
2b57c43f
...
@@ -415,7 +415,7 @@ Changes in Python behavior
...
@@ -415,7 +415,7 @@ Changes in Python behavior
* Yield expressions (both ``yield`` and ``yield from`` clauses) are now disallowed
* Yield expressions (both ``yield`` and ``yield from`` clauses) are now disallowed
in comprehensions and generator expressions (aside from the iterable expression
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`.)
(Contributed by Serhiy Storchaka in :issue:`10544`.)
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment