thilinarmtb
thilinarmtb

Reputation: 239

Returning generators in 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.

Upvotes: 3

Views: 4324

Answers (2)

theodox
theodox

Reputation: 12208

You cant have returns inside a generator expression.

In Python 2.X you have to chain the generators manually:

 def normal(start):

    term = start
    while True:
        yield term
        term = term + 1

 def iterate(start, inc):
    if inc == 1:
       for item in normal(start):
           yield item
    else:
        term = start
        while True:
            yield term
            term = term + inc

I'm assuming you know both of these examples will run forever :)

FWIW in your original example you could clean it up by making two generators (say, 'mormal' and 'abnormal') and then returning one or the other from the iterate function. As long as you're not mixing generators and returns you can return generators... so to speak...

 #using original 'normal'

 def abnormal(start, inc):
    term = start
    while True:
        yield term
        term = term + inc

 def iterate (start, inc):
    if inc == 1: 
       return normal(start)
    return abnormal(start, inc)

Upvotes: 4

BrenBarn
BrenBarn

Reputation: 251365

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.

Upvotes: 6

Related Questions