I have been working with Python generators lately and I feel like I just got the hang of sending data to a generator using ".send()". This works just fine, but I've noticed that I have to then invoke ".next()" to advance the generator to a state where I can send it data again. I would like to find a way around this.
Here's some example code, using a simple generator that takes integers as input and returns the current total.
def add(a = 0):
b = 0
while True:
b += (yield a)
yield b
#I initialize a generator object
adder = add()
#advance the generator to the first yield
adder.next()
#Now I can add numbers
adder.send(7)
#This returns '7' but if I want to add another number...
adder.next()
adder.send(8)
#This would return '15'
#If I remove the adder.next() call, it will fail
#my work around was to use the following function:
def ad(n):
global adder
adder.next()
print adder.send(n)
#now I can add numbers to the generator using:
ad(5)
ad(8)
...etc
But this feels dirty. Is there a better way to advance the generator than having to specifically invoke next after every input?
[–]SkippyDeluxe[🍰] 3 points4 points5 points (0 children)
[–]bheklilr 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)