Reputation: 4767
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.
Upvotes: 0
Views: 43
Reputation: 9664
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)
.Upvotes: 1