This is just a small improvement, but worthwhile. It's intuitive IMO to be able to use similar filtering expressions to comprehensions at the top of a for loop.

Here's an example:

# get the Hadoop version by scanning pyspark jars.
# Vague attribution: 
for path in Path("pyspark/jars")).glob("hadoop-*.jar") if not path.stem.startswith("hadoop-shaded-guava"):
    name, _, version = path.stem.rpartition("-")

glob is already a filtering mechanism. It's just not *quite* flexible enough to give just the items I want. I'd like to be able to enter the loop with only file names of interest.

–Michael A. Smith

On Tue, Mar 1, 2022 at 21:51 Paul Bryan <pbryan@anode.ca> wrote:
1. It aligns with existing syntax in list comprehensions and generator expressions.
2. In probably majority of cases it would be more readable to me; "iterate over iterable for items meeting condition:".
3. Could it be easier to optimize an explicit filter expression to improve iteration performance?

On Wed, 2022-03-02 at 13:37 +1100, Steven D'Aprano wrote:
On Wed, Mar 02, 2022 at 02:28:33AM +0100, Svein Seldal wrote:

    for x in y if x in c:

What does this new syntax give us that we don't already have with this?

    for x in y
        if x in c:

or the other multiple ways of writing the equivalent code?

I see no new functionality here. Is the only advantage that you save one
line and one indent level? Both are cheap.

To be precise, one extra line in something which is already a multiline
statement is essentially insignificant, and while an extra indent level
*can* be important, if you have already used so many indents that it
becomes important, you probably should be refactoring your code.

All I see here is adding to the complexity of the parser and the
language for no meaningful benefit. Its not even easier to read, it
crams more on one line which in real code with meaningful variable names
and a meanigful condition starts to get a bit long:

    # this line desperately needs to be split over two lines
    for student in students if mean(student.grade(subject) for subject in student.get_subjects()) > 0.8):

When I write list comprehensions with an if condition, probably 90% of
the time I end up moving the if condition to a second or even third line
of the comprehension. I expect the same will apply here.

To save one line for maybe 10% of my for...if constructs, I don't think
it is worth the bother of adding yet another way to do it.

Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/KTM6XDMOMQW4W7XRDMG7S65EL34GXAZG/
Code of Conduct: http://python.org/psf/codeofconduct/