[Python-ideas] if-statement in for-loop

Steven D'Aprano steve at pearwood.info
Tue Oct 4 12:07:42 EDT 2016


On Tue, Oct 04, 2016 at 01:31:22PM +1000, Nick Coghlan wrote:

> By contrast, eliminating the vertical whitespace without actually
> reducing the level of nesting is merely hiding the readability problem
> without actually addressing it.

+1

Extra newlines are cheap. Writing

    for x in expression:
        if condition:
            block

is a simple, clean idiom that is easy to understand, avoids a number of 
pitfalls (where do you put the elif or else if you need one?), and only 
costs one extra line and one extra indent. If you have so many indents 
that this is a problem, that's a code smell and you ought to think more 
closely about what you are doing.

There's another variation that saves an indent for the cost of one more 
line:

    for x in expression:
        if not condition:
            continue
        block


In contrast, comprehensions are a single expression and are expected to 
usually be written in one line, although that's often hard to do without 
very long lines. They cannot include elif or else clauses, so avoid 
that particular pitfall. But the "very long line" problem shows that 
they are too dense: simple examples look fine:

    [x+1 for x in seq if cond]

but in practice, they're often much longer with a much higher density of 
code:

    [default if obj is None else obj.method(arg) for (obj, count) in zip(values, counts) if count > 1]

Some compromise on the optimal level of readability and code density is 
allowed: that's the price we pay in order to squeeze everything into a 
single expression. But that is not something we ought to copy when we 
have the luxury of a suite of statements.



-- 
Steve


More information about the Python-ideas mailing list