[Python-ideas] With clauses for generator expressions
Guido van Rossum
guido at python.org
Sat Nov 17 00:50:45 CET 2012
On Fri, Nov 16, 2012 at 3:28 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Nick Coghlan wrote:
>> That is, the outermost iterable is evaluated in the *current* scope, not
>> inside the generator.
> I've always felt it was a bad idea to bake this kludge into
> the language. It sweeps a certain class of problems under the
> rug, but only in *some* cases. For example, in
> ((x, y) for x in foo for y in blarg)
> rebinding of foo is guarded against, but not blarg. And if
> that's not arbitrary enough, in the otherwise completely
> ((x, y) for y in blarg for x in foo)
> it's the other way around.
I wouldn't call it arbitrary -- the second and following clauses
*must* be re-evaluated because they may reference the loop variable of
the first. And the two versions you show aren't equivalent unless
iterating over blarg and foo is completely side-effect-free.
> Anyhow, it wouldn't be *impossible* to incorporate a with-clause
> into this scheme. Given
> (upper(line) with open(name) as f for line in f)
> you either pick open(name) to be the pre-evaluated expression,
> or not do any pre-evaluation at all in that case. Either way,
> it can't break any *existing* code, because nobody is writing
> genexps containing with-clauses yet.
And nobody ever will. It's too ugly.
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas