[Python-Dev] Tricky way of of creating a generator via a comprehension expression

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Nov 23 03:11:37 EST 2017


Ivan Levkivskyi wrote:
> "People sometimes want to refactor for-loops containing `yield` into a 
> comprehension but that doesn't work (particularly because of the hidden 
> function scope) - lets make it a SyntaxError"

Personally I'd be fine with removing the implicit function
scope from comprehensions and allowing yield in them, since
the semantics of that are clear.

But I don't see a way to do anything equivalent with
generator expressions. Since the current effect of
yield in a generator expression is pretty useless,
it seems best just to disallow it.

That means a list comprehension won't be equivalent
to list(generator_expression) in all cases, but I
don't think there's any great need for it to be.

-- 
Greg


More information about the Python-Dev mailing list