Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning generators in python

Tags:

python

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.

like image 219
thilinarmtb Avatar asked Mar 04 '26 03:03

thilinarmtb


1 Answers

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.

like image 95
BrenBarn Avatar answered Mar 05 '26 17:03

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!