[Python-ideas] if in for-loop statement
Steven D'Aprano
steve at pearwood.info
Thu Feb 23 13:25:46 EST 2017
On Thu, Feb 23, 2017 at 01:37:15PM +0000, Henk-Jaap Wagenaar wrote:
[...]
> Other solutions to another case of this 'problem' are discussed has been
> discussed on StackOverflow (
> http://stackoverflow.com/questions/6981717/pythonic-way-to-combine-for-loop-and-if-statement)
> where it is suggested one uses a generator expression before the loop. None
> of these solutions seem very Pythonic to me.
Indeed not. The Pythonic solution is exactly the one you used: DON'T
combine the for-loop and if-statement.
for x in range(100):
if is_prime(x):
...
If the use of two lines and two indents is truly a problem, to the point
that you really need to refactor to a single line, that's a code smell:
your function is probably too big, too complex and does too much, and
should be refactored.
> - it would mean there is a Pythonic solution to a current 'problem' that
> does not have one.
It does have a solution: "Don't do it".
One common argument is that people can write a for...if in a single
expression as part of comprehensions:
[... for x in range(100) if is_prime(x)]
so they should be able to write the same outside. We can write:
[... for x in seqA for y in seqB if y for z in seqC]
Does that mean we should be able to write this as a combined statement?
for x in seqA for y in seqB if y for z in seqC:
...
Certainly not! The fact that comprehensions allow such ugly code is not
a feature to be emulated, but something to be discouraged.
Comprehensions are limited to being a single expression, and so we have
to compromise on good design in order to get the full functionality
required. No such compromise is needed with the statement forms of
for/if. We can draw the line right at the start, and insist that each
statement falls on a line on its own.
Deeply nested for...for...for...if...if...if...for... blocks look ugly
because they are ugly. Allowing them all on one line makes the Python
language worse, not better. It is unfortunate that comprehensions, by
their nature, must allow that sort of thing, but that doesn't mean we
have to allow it elsewhere.
--
Steve
More information about the Python-ideas
mailing list