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

Serhiy Storchaka storchaka at gmail.com
Wed Nov 22 08:03:09 EST 2017


     g = [(yield i) for i in range(3)]

Syntactically this looks like a list comprehension, and g should be a 
list, right? But actually it is a generator. This code is equivalent to 
the following code:

     def _make_list(it):
         result = []
         for i in it:
             result.append(yield i)
         return result
     g = _make_list(iter(range(3)))

Due to "yield" in the expression _make_list() is not a function 
returning a list, but a generator function returning a generator.

This change in semantic looks unintentional to me. It looks like leaking 
an implementation detail. If a list comprehension would be implemented 
not via creating and calling an intermediate function, but via an 
inlined loop (like in Python 2) this would be a syntax error if used 
outside of a function or would make an outer function a generator function.

     __result = []
     __i = None
         for __i in range(3):
             __result.append(yield __i)
         g = __result
         del __result, __i

I don't see how the current behavior can be useful.

More information about the Python-Dev mailing list