[Python-ideas] Allowing breaks in generator expressions by overloading the while keyword

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Feb 21 17:36:56 CET 2014


On 21 February 2014 12:18, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 21 February 2014 20:24, Steven D'Aprano <steve at pearwood.info> wrote:
>>
>> but alas both Nick Coglan and (if I recall correctly) Guido have ruled
>> that Python won't get this, so until the Revolution comes, it isn't
>> going to happen.
>
> It's not that it can't happen - it's that someone would need to build
> a case of a similar calibre to the one Chris Angelico is currently
> putting together for except expressions in PEP 463 :)
>
> However, it's a *much* bigger challenge in this case, as
> itertools.takewhile exists, whereas there's currently no way to do
> exception handling as part of a larger expression without major
> contortions.

I think the two are very similar. PEP 463 proposes that you could do

    item = stuff['name'] except KeyError: 'default'

which you can already do in an ugly sort of way with a helper function:

    item = catchdefault(lambda: stuff['name'], KeyError, 'default')

This proposal is that you could do:

    isprime = all(n % p for p in primes_seen while p ** 2 <= n)

which you can already do in an ugly sort of way with a helper function

    isprime = all(n % p for p in takewhile(lambda p: p**2 <= n, primes_seen))

Neither syntax proposal gives anything that fundamentally can't be
done with helpers and lambda functions. Both syntax ideas are about
finding an intuitive and readable way of representing commonly used
patterns without too much visual clutter.

Similarly in either case you could just refactor the ugly part out
into a different function. But splitting code up into different
functions also comes with a readability cost. Do you think that the
following is any clearer than either of the previous two?

    isprime = all(n % p for p in take_le_sqrt(primes_seen, n))


Oscar


More information about the Python-ideas mailing list