[Python-ideas] With clauses for generator expressions

Terry Reedy tjreedy at udel.edu
Thu Nov 15 18:54:49 CET 2012

On 11/15/2012 6:11 AM, Andrew Barnert wrote:
>> From: Phil Connell <pconnell at gmail.com>

>> While this  looks very clean, how do you propose the following should be
>> written
>> as a  generator expression?
>> def foo():
>>      with open('foo') as  f:
>>          for line in f:
>>               if 'bar' in line:
>>                   yield line
> Exactly as you suggest (quoting you out of order to make the answer clearer):
>> (line
>> for line in f
>> if bar in 'line'
>> with open('foo') as f)

The simple rule for comprehensions is that the append (l.c.) or yield 
(g.e) is moved from last to first and the other statements/clauses are 
left in the same order.

> Which means the only question is, which one looks more readable:
> 1. (foo(line) for line in baz(f) if 'bar' in line with open('foo') as f)
> 2. (foo(line) for line in baz(f) with open('foo') as f if 'bar' in line)
> 3. (foo(line) with open('foo') as f for line in baz(f) if 'bar' in line)

Which means that 3 is the proper one. In particular, if with clauses 
were added, f must be defined in the with clause before used in the for 
clause, just as line must be defined in the for clause before used in 
the if clause.

Terry Jan Reedy

More information about the Python-ideas mailing list