This has been discussed many times, including these:
if-statement in for-loop
if-syntax for regular for-loops
for-loop-if like list comps have?
Syntax proposal of for…in…if in regular for loops
The benefit is negligible:
-
you save one line, and one indent level;
-
new lines are cheap, who cares about one line?
-
indents are not so cheap, but if your code has so many indents that this becomes important, you probably should refactor your code.
Often, you can’t use this, because the line length will exceed your style guide’s limit on line length, so you will need to split into two lines anyway:
Even if your style guide allows unreasonably long lines, long lines are much harder to read so this will hurt readability, not help it.
Simple cases might be okay:
for obj in seq if cond:
...
but more realistic examples are not so good:
for ext in ('.py', '.pyc', '.pyo') if os.path.isfile(os.path.join(path, '__init__' + ext)):
...
The for...if
line is 91 columns. Too long! Put it inside a method of a class, and you have 99 columns. Even worse.
So my opinion is:
-
one more special case for people to learn about Python’s syntax;
-
usually hurts readability, not helps;
-
more complicated language rules, for negligible benefit.
The big difference between this proposal and list comprehensions is not the “save one line” part, but that comprehensions are expressions that can be used in other parts of code, but this is a statement.
When I have long comprehensions, I almost always split them over multiple lines, and usually at the “if”:
result = function(arg, obj,
[long_expression for x in some_sequence
if some_long_condition],
key=something)
so saving a line in a loop is just not that important to me.