[Python-ideas] With clauses for generator expressions

Andrew Barnert abarnert at yahoo.com
Thu Nov 15 11:37:58 CET 2012


> From: Serhiy Storchaka <storchaka at gmail.com>
> Sent: Thu, November 15, 2012 1:05:27 AM
> 
> On 15.11.12 05:44, Andrew Barnert wrote:
> > That's why we still have tons  of code like this lying around:
> >
> >      upperlines =  (lines.upper() for line in open('foo', 'r'))
> >
> > Everyone knows that  this only works with CPython, and isn't even quite 
right
> > there, and yet  people write it anyway, because there's no good alternative.
> 
> Not every  piece of code should be written as one-liner.

But a piece of code that everyone needs on a regular basis should be writable, 
and readable, by a novice Python user. I don't care whether it's one line or 
four, but I do care that a task that seems to require nothing that you don't 
learn in your first week with the language is beyond the ability of not just 
novices, but people who post modules on PyPI, write answers on StackOverflow, 
etc.

> Use a generator function.

Of course the right answer is obvious to you and me, because we understand the 
difference between static and dynamic scopes, and that a generator defines a 
dynamic scope, and what context managers actually do, and how to translate a 
generator expression into a generator function.

It's not that the generator function is hard to write; it's that people who 
don't understand how all this stuff works won't even think of the idea that an 
explicit generator function would help them here.



More information about the Python-ideas mailing list