PEP 479: Fix formatting of examples.

This commit is contained in:
Guido van Rossum 2014-11-20 21:14:17 -08:00
parent 89c4b9ef1f
commit 9ef2ed8f5d
1 changed files with 17 additions and 0 deletions

View File

@ -106,25 +106,33 @@ changed to simply return instead. This will be compatible with all
existing Python versions, and will not be affected by __future__.
Lib/ipaddress.py::
if other == self:
raise StopIteration
Becomes::
if other == self:
return
In some cases, this can be combined with ``yield from`` to simplify
the code, such as Lib/difflib.py::
if context is None:
while True:
yield next(line_pair_iterator)
Becomes::
if context is None:
yield from line_pair_iterator
return
(The ``return`` is necessary for a strictly-equivalent translation,
though in this particular file, there is no further code, and the
``return`` can be elided.) For compatibility with pre-3.3 versions
of Python, this could be written with an explicit ``for`` loop::
if context is None:
for line in line_pair_iterator:
yield line
@ -132,6 +140,7 @@ of Python, this could be written with an explicit ``for`` loop::
More complicated iteration patterns will need explicit try/catch
constructs. For example, a parser construct like this::
def unwrap(f):
while True:
data = next(f)
@ -140,7 +149,9 @@ constructs. For example, a parser construct like this::
if line == "- end -": break
data += line
yield data
would need to be rewritten as::
def parser(f):
while True:
try:
@ -152,7 +163,9 @@ would need to be rewritten as::
yield data
except StopIteration:
return
or possibly::
def parser(f):
for data in f:
while True:
@ -186,9 +199,11 @@ no value to return. In this, it is similar to ``__getattr__`` (can
raise ``AttributeError``), ``__getitem__`` (can raise ``KeyError``),
and so on. A helper function for an iterator can be written to
follow the same protocol; for example::
def helper(x, y):
if x > y: return 1 / (x - y)
raise StopIteration
def __next__(self):
if self.a: return helper(self.b, self.c)
return helper(self.d, self.e)
@ -201,8 +216,10 @@ A generator function is one which contains a ``yield`` expression.
Each time it is (re)started, it may either yield a value, or return
(including "falling off the end"). A helper function for a generator
can also be written, but it must also follow generator protocol::
def helper(x, y):
if x > y: yield 1 / (x - y)
def gen(self):
if self.a: return (yield from helper(self.b, self.c))
return (yield from helper(self.d, self.e))