Recursion using yield

Yes, you can do this:

def infinity(start):
    yield start
    for x in infinity(start + 1):
        yield x

This will error out once the maximum recursion depth is reached, though.

Starting from Python 3.3, you’ll be able to use

def infinity(start):
    yield start
    yield from infinity(start + 1)

If you just call your generator function recursively without looping over it or yield from-ing it, all you do is build a new generator, without actually running the function body or yielding anything.

See PEP 380 for further details.

Leave a Comment