[Python-ideas] More power in list comprehensions with the 'as' keyword

Josiah Carlson josiah.carlson at gmail.com
Fri Aug 29 08:43:31 CEST 2008

On Thu, Aug 28, 2008 at 11:33 PM, Cesare Di Mauro
<cesare.dimauro at a-tono.com> wrote:
> On 28 agu 2008 at 22:37:20, Terry Reedy <tjreedy at udel.edu> wrote:
>> To parallel the Haskell-ish example, this should be
>> [stripped for l in text.split('/n') stripped as l.strip() if stripped != '']
>> but the clause has 'as' in the middle instead of at the beginning,
>> making it hard to parse.  Haskell used commas
>> [stripped for l in text.split('/n'), stripped as l.strip(), if stripped
>> != '']
>> but I think this would conflict with Python's other comma usage.  Most
>> feasible, I think, would be
>> [stripped for l in text.split('/n') with stripped as l.strip() if
>> stripped != '']
>> This corresponds to the multi-statement for loop version
>> _=[]
>> for l in text.split('\n'):
>>    stripped = l.strip()
>>    if stripped != '':
>>      _.append(stripped)
>> with 'stripped = l.strip()' replaced by 'with stripped as l.strip()'.
>> If other use cases were presented that could not be more easily written
>> otherwise, as with the re.split() version, I might at least be neutral
>> on this.
>> Terry Jan Reedy
> We already a "with Expression as Identifier" syntax that is well known
> and used in Python: why use something different?
> [stripped for l in text.split('\n') with l.strip() as stripped if stripped != '']
> will be a much better syntax to parse and acquire for a typical
> pythonista. ;)

Just because it exists, doesn't mean that it's "well known and used".
Also, don't conflate the need to handle context management (locking,
closing files, etc.) with the false perceived need to add temporary
assignments in list comprehensions and generator expressions.

 - Josiah

More information about the Python-ideas mailing list