Conditional loop filtering

Python comprehension expressions have filtering built in:

[thing.foo for thing in bunch_of_things if thing.bar > 42]

But in regular loops we need to do this:

for thing in bunch_of_things:
    if thing.bar > 42:
        do_something_with(thing.foo)

It would be nice to have the same type of filtering in the loops as well:

for thing in bunch_of_things if thing.bar > 42:
    do_something_with(thing.foo)

Any thoughts?

See my proposal for a similar syntax for “filtered” assignment and “filtered” returns Conditional Expresion/Statements

And see this proposal to have “filtered” context managers: Conditional context manager (with foo() if bar)

I guess one of the answers you are going to get is that you can also do

for thing in (y for y in bunch_of_things if y.bar > 42):
    do_something_with(thing.foo)

which of course it is not convoluted at all (filter can also be applied here with a lambda)

Whereas I would tend to see a slowly emerging pattern … people want to have things conditionally executed with an if statement at the end.

My 2 cents.

Previous discussions:

1 Like

Yes, I am aware of all these options, and still think that the approach I outlined is the most viable.

  1. It already exists as syntax (in comprehensions).
  2. There is some similarities to the “conditional statements” proposal, but I think that that one opens quite a can of edge cases.
  3. It’s orthogonal to the context manager proposal.
  4. It’s much simpler than either the comprehension or filter options, which are the current workarounds.

Whereas I would tend to see a slowly emerging pattern … people want to have things conditionally executed with an if statement at the end.

This proposal is strictly about in-loop filtering, not any arbitrary execution. It is also in line with existing syntax of comrehensions (which were originally modelled after loops).

Thank you Chris, I missed those. :pray:

OK, reading through these threads I realise that the damage has already been done by allowing if expressions to have different syntax in comprehensions from the basic loops. So we can’t implement this idea without breaking backward compatibility, even taking into account that if..else is extremely rarely used in for loops.

1 Like