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

Nick Coghlan ncoghlan at gmail.com
Mon Oct 3 23:31:22 EDT 2016


On 4 October 2016 at 08:18, Erik <python at lucidity.plus.com> wrote:
> The expression suggested could be spelled:
>
> for i in range(10): if i != 5:
>     body
>
> So, if a colon followed by another suite is equivalent to the same construct
> but without the INDENT (and then the corresponding DEDENT unwinds up to the
> point of the first keyword) then we get something that's pretty much as
> succinct as Dominik suggested.

What's the pay-off though? The ultimate problem with deeply nested
code isn't the amount of vertical whitespace it takes up - it's the
amount of working memory it requires in the brain of a human trying to
read it. "This requires a lot of lines and a lot of indentation" is
just an affordance at time of writing that reminds the code author of
the future readability problem they're creating for themselves.

Extracting named chunks solves the underlying readability problem by
reducing the working memory demand in reading the code (assuming the
chunks are well named, so the reader can either make a useful guess
about the purpose of the extracted piece without even looking at its
documentation, or at least remember what it does after looking it up
the first time they encounter it).

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

Cheers,
Nick.

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


More information about the Python-ideas mailing list