Understanding this generator function

H

Hussein B

Hey,
This is an example of a generator function:
=====
def counter(start_at=0):
count = start_at
while True:
val = (yield count)
if val is not None:
count = val
else:
count += 1
======9
======
I'm not able to understand how this generator function is working,
would you please me (what happens when calling next/send)?
Thanks.
 
J

James Mills

Hi,

There is a great set of slides on this topic
available here: http://www.dabeaz.com/generators/

They explain this concept quite well and
walk you through everything you need to
know about generators and how powerful
they can be.

Please read it.

cheers
James
 
J

Jeff

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top