I want to do something analogous to the following:
def normal(start):
term = start
while True:
yield term
term = term + 1
def iterate(start, inc):
if inc == 1:
return normal(start)
else:
term = start
while True:
yield term
term = term + inc
Now this gives the following error.
SyntaxError: 'return' with argument inside generator
How I can return a generator to one function through another? (Note: Example shown here doesn't require this kind of functionality but it shows what I need to do)
Thanks in advance.
Starting in Python 3.3, you can use yield from normal(start) as described in PEP 380. In earlier versions, you must manually iterate over the other generator and yield what it yields:
if inc == 1:
for item in normal(start):
yield item
Note that this isn't "returning the generator", it's one generator yielding the values yielded by another generator. You could use yield normal(start) to yield the "normal" generator object itself, but judging from your example that isn't what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With