[Python-ideas] PEP 479: Change StopIteration handling inside generators

Ian Foote ian at feete.org
Wed Nov 26 00:19:01 CET 2014


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 25/11/14 21:56, random832 at fastmail.us wrote:
> On Tue, Nov 25, 2014, at 15:31, Chris Barker wrote:
>> Once you start nesting these things, the distinction between 
>> "implementor" and "caller" gets mingled. And I think this is all
>> about how nested generators behave, yes?
> 
> For something more concrete, we can consider a naive implementation
> of iteration over adjacent pairs:
> 
> def pairs(x): i = iter(x) while True: yield next(i), next(i)
> 

<snip>

> 
> To work under the new paradigm, you need to catch StopIteration 
> explicitly:
> 
> def pairs(x): i = iter(x) while True: try: a = next(i) b = next(i) 
> except StopIteration: return yield a, b
> 

You're right that you need to catch the StopIteration, but it seems to
me the natural way to write your second example is:

def pairs(x):
    i = iter(x)
    while True:
        try:
            yield next(i), next(i)
        except StopIteration:
            return

Adding the extra variables a and b is unnecessary and distracts from
the change actually required.

Regards,
Ian F
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQEcBAEBAgAGBQJUdQ5lAAoJEODsV4MF7PWz/zsIALLI67/W+HAG3l0Xe+kd2/Xw
QEI5NrOyT/izRHbV69K3zvOVKKCfiUXjkK5rPGxFiBmF96hOmQyro7Z4UiCSYzsT
N+8dy8M6/gAWolEbD1EZoXZorNHa9nsZ8q3hBltl824CAl4Kx7FFKssUVIFWjyrD
IgPjI4PIJBl12uX9F9VLMaBjfEy+QiCUa3a8s7ZdqS1asm1M4udei/qvt1t/NaIL
uoYGuBO/mzxP9sdWtP4z53sX07gOMPUWdBTXFX91+G1pCaUuGCHpDcHwexatxVgk
JxgfajyadFj+44QeHpsY10pu0HhaRH+Cbg7vADa2KQ6N3kQic1qHR9FkcHCvaA0=
=SdtN
-----END PGP SIGNATURE-----


More information about the Python-ideas mailing list