[Python-ideas] Is this PEP-able? for X in ListY while conditionZ:

Nick Coghlan ncoghlan at gmail.com
Sun Jun 30 01:51:43 CEST 2013


On 30 June 2013 01:56, Steven D'Aprano <steve at pearwood.info> wrote:
> In fact, I would argue the opposite, it's not *simpler* it is *more complex*
> because it is a special case for the if keyword:
>
> break if condition  # allowed
> continue if condition  # maybe allowed?
> return 'spam' if condition  # probably disallowed
> pass if condition  # what's the point?
> raise Exception if condition  # probably disallowed
> x += 1 if condition  # almost certainly disallowed

People already have to learn "for/else" and "while/else". Adding
"break if" can *only* be justified on the grounds of pairing it up
with those two existing else clauses to make appropriate if/else
pairs, as "for/break if/else" and "while/break if/else" should
actually be easier to learn than the status quo.

However, note that I said "I would love to see this idea written up as
a PEP", not "I would love to see this idea implemented as part of the
language": I'm undecided on that point as yet. It at least has the
*potential* to make an existing aspect of the language easier to learn
(unlike every other suggestion in any of these threads). Including a
plan to deprecate allowing loop else clauses without a corresponding
"break" in such a PEP would be a good idea, though.

Expanding it to comprehensions is indeed trickier, because the "break"
doesn't quite scan correctly. While Joshua said he wasn't proposing
it, permitting a semi-colon in the comprehension to separate out a
termination clause actually reads pretty well to me (we can avoid
ambiguity in the grammar because we don't currently allow ';' anywhere
between any kind of bracket):

   [x for x in iterable; break if x is None]
   [x for x in data if x; break if x is None]

One nice advantage of that notation is that:

1. The statement after the ";" is exactly the statement that would
appear in the expanded loop
2. It can be combined unambiguously with a filtering clause
3. It clearly disallows its use with nested loops in the comprehension

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list