On Tue, Mar 01, 2022 at 10:40:06PM -0500, Michael Smith wrote:
+1
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.
Good news! We have been able to use filtering conditions at the top of a for loop since Python 1.5 or even earlier, back in the 1990s. And the excellent thing about the existing syntax is that we can split the for loop and the filter onto separate lines for enhanced readablity, without needing to add extraneous parentheses and indent. # Don't need this. for student in students if ( mean(student.grade(subject) for subject in student.get_subjects()) > 0.8) ): ... # Can do this. for student in students: if mean(student.grade(subject) for subject in student.get_subjects()) > 0.8): ... And if you are thinking right now "Huh, there is hardly any difference between the two, what's the big deal?" -- exactly. Outside of pretend code with one letter variable names, `for a in b if c`, the actual benefit in real code is extremely minor, if any. In most cases you're going to split the line over two lines anyway, and if you find yourself worried about saving an indent, almost surely your code needs refactoring.
Here's an example:
# get the Hadoop version by scanning pyspark jars. # Vague attribution: https://stackoverflow.com/a/50242383 for path in Path("pyspark/jars")).glob("hadoop-*.jar") if not path.stem.startswith("hadoop-shaded-guava"):
Ironically, your one line loop and filter was word-wrapped because the line was too long. Do you use black or PEP8? Do the projects you work on enforce 79 column or even 100 column coding standards? Then your example, with 106 columns, will have to be split over two lines. Which is my point. This suggestion sounds good, but in real code, you probably can't use it. And even if you can, it doesn't make it any easier to write loops with filters, or add the ability to do something new that we can't easily do now. It is purely a cosmetic change, and not even a very interesting cosmetic change. -- Steve