[Python-Dev] Tricky way of of creating a generator via a comprehension expression (original) (raw)
Ethan Furman ethan at stoneleaf.us
Wed Nov 22 12:37:55 EST 2017
- Previous message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Next message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 11/22/2017 05:03 AM, Serhiy Storchaka wrote:
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 makelist(it): result = [] for i in it: result.append(yield i) return result g = makelist(iter(range(3))) Due to "yield" in the expression makelist() is not a function returning a list, but a generator function returning a generator.
The [] syntax says g should be list. Seems to me we could do either of:
- raise if the returned object is not a list;
- wrap a returned object in a list if it isn't one already;
In other words, (2) would make
g = [(yield i) for i in range(3)]
and
g = [((yield i) for i in range(3))]
be the same.
I have no idea how either of those solutions would interact with async/await.
--
Ethan
- Previous message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Next message (by thread): [Python-Dev] Tricky way of of creating a generator via a comprehension expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]