0

What would be the difference between the following two generator functions?

def get_primes(number):
    while True:
        if is_prime(number):
            number = yield number
        number += 1

And:

def get_primes(number):
    while True:
        if is_prime(number):
            yield number
        number += 1

As far as I understand, I can call them as:

p = get_primes(0)

# first call works for both
next(p) # or p.send(None)

# second call different for both
next(p)    # works for second way only
p.send(14) # works for first way only

I think my issue is I don't really understand how send works and how it's setting the value and all.

2
  • 1
    The first one allows you to send a new value for number, and fails if you don't. If you call next without sending a value, then number will be None and then number += 1 raises a TypeError. Commented Feb 28, 2020 at 1:45
  • @kaya3: Though it could be made to work fairly easily by accepting into a different name, and only moving it to number if the value sent was non-None. Commented Feb 28, 2020 at 1:49

1 Answer 1

1

If you check out the docs, it says:

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression.

That may sounds a little cryptic, so perhaps in other words:

Using send() the generator resumes where it yielded and the value you have sent is what yield returns (and can be assigned to any variable). You can also try the following code:

def get_num():
    number = 1
    while True:
        print(number)
        number = yield number

g = get_num()
g.send(None)  # haven't yielded yet, cannot send a value to it
g.send(2)
g.send(5)

It'll return:

  • 1: value we've initially assigned to number
  • 2: we did send(2) and that is what number = yield ... assigned to number, then we continued, looped back to print() and yielded again.
  • 5: Same thing, but we did send(5).
Sign up to request clarification or add additional context in comments.

3 Comments

cool, can also examine what it's storing by doing g.gi_frame.f_locals.
Also -- to clarify, it first returns the yield statement and after assigns the value from send to number, correct?
Yes, it yields and suspends there. Using send() the generator resumes with yield returning (having, inside the generator) sent value and continues execution until it yields again (or ends).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.