RFC: For Loop Invariants

Juergen Brendel juergen at brendel.com
Fri Apr 10 20:09:33 EDT 2020


Hello!

On Fri, 2020-04-10 at 15:44 -0500, Elliott Dehnbostel wrote:
> chars = "abcaaabkjzhbjacvb"
> seek = {'a','b','c'}
> count = 0
>
> for a in chars if a in seek: count += 1

Interesting proposal. However, I'm not sure how much benefit it really
will give us in practice. Reason being: Conditions are often not
trivial, descriptive variable names are often not super short. Before
you know it, the expressions for the iterable and for the condition are
long enough to go past your project's max line-width. And then suddenly
you are left with something worse than two indents: A line break and
continuation of a for-loop/if-condition (those are the worst).

    for my_well_names_variable in some_complex_iterable \
            if a_complex_condition_that_needs_to_be_evaluated:
        count += 1

Or maybe:

    for (my_well_names_variable in some_complex_iterable
         if
a_complex_condition_that_needs_to_be_evaluated):
        count += 1

Or maybe:

    for my_well_names_variable in some_complex_iterable \
        if a_complex_condition_that_needs_to_be_evaluated:
        count += 1

None of those are nice. That's a general issue with line-breaks in for-
loops or if-condition and has nothing to do with your proposal
specifically.


I think this here is more readable and less prone to errors:

    for my_well_names_variable in some_complex_iterable:
        if a_complex_condition_that_needs_to_be_evaluated:
            count += 1

All in all, I like the proposal, but I'm not sure it would buy us that
much. Specifically, I'm not sure that it would help a lot with
readability and may end up making it worse, since you'll have a higher
chance of having those line-breaks.

Juergen





More information about the Python-list mailing list