[Python-ideas] With clauses for generator expressions

Nick Coghlan ncoghlan at gmail.com
Fri Nov 16 01:46:28 CET 2012


On Fri, Nov 16, 2012 at 1:25 AM, Andrew Barnert <abarnert at yahoo.com> wrote:

> My use case was at the top of my first email:
>
>     upperlines = (line.upper() for line in file with open(path, 'r') as
> file)
>

And it's *awful*. If the only thing on the RHS of a simple assignment
statement is a lambda or generator expression, that code should almost
always be rewritten with def as a matter of style, regardless of other
considerations.

However, I realised there's a more serious problem with your idea: the
outermost clause in a list comprehension or generator expression is
evaluated immediately and passed as an argument to the inner scope that
implements the loop, so you have an unresolved sequencing problem between
the evaluation of that argument and the evaluation of the context manager.
If you want the context manager inside the generator, you *can't* reference
the name bound in the as clause in the outermost iterable.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20121116/55497f1a/attachment.html>


More information about the Python-ideas mailing list