Request for elucidation: enhanced generators
Ant
antroy at gmail.com
Wed Sep 20 09:46:34 EDT 2006
Ben Sizer wrote:
...
> But do you have an example of such a use case? That's what I'm missing
> here.
I've been looking at this myself, trying to understand the point of
coroutines. I believe that they boil down to generators which are able
to take in data as well as provide it. A simple way of looking at it
seems to be that a coroutine is a generator which can have its state
changed whilst it is still active. A silly example to illustrate:
# coroutine.py
def stateful_generator(people):
greeting = "Hello"
for person in people:
received = (yield greeting + " " + person)
if received:
greeting = received
if __name__ == "__main__":
people = ["bob", "henry", "jim-lad", "boney", "greebo", "badger"]
gen = stateful_generator(people)
print gen.next() # Hello bob
print gen.next() # Hello henry
print gen.send("Yo! ") # Yo! jim-lad
print gen.next() # Yo! boney
print gen.send("Meow ") # Meow greebo
print gen.next() # Meow badger
So you can change the behaviour of the coroutine whilst it is running.
That's as far as I have got with them though - there are presumably
many other uses of coroutines out there as I guess this use case could
be simulated using generators and globals.
More information about the Python-list
mailing list