Understanding this generator function

Jeff jeffober at gmail.com
Wed Aug 27 07:58:01 EDT 2008


> def counter(start_at=0):
>     count = start_at
>     while True:
>         val = (yield count)

A generator can accept a value from the consumer.  So, If I have a
counter:

  c = counter()

I can send it a value:

  c.send(9)

>         if val is not None:
>             count = val

The generator tests to see it it received anything, and if it does,
resets count to what it received (in this case, 9).

>         else:
>             count += 1

Otherwise, it just increments count on each call.



More information about the Python-list mailing list