What is yield and yield from in Python (#dev #python)

What is yield and yield from in Python

Overview

In this post, we’ll talk about the yield and yield from keywords in Python. We’ll see how they work, and how you can use them to create generators and coroutines.

What is yield in Python?

Well, it’s basically the same as in C# or other programming languages…

Queue the theme for The Office!

Just kidding! 😂 The yield keyword in Python is used to create a generator, which we talked about in length here.

So a quick recap:

def infinite_numbers():
    i = 0
    while True:
        yield i
        i += 1
        
for number in infinite_numbers():
    print(number)

In the example above, we’re creating a generator that will yield an infinite number of integers. The yield keyword is used to return a value from the generator, and it will pause the execution of the generator until the next time it’s called.

And what about yield from?

It is almost the same thing, but you can use it to delegate the yield to another generator. Example:

def even_numbers(n):
    for i in range(n):
        if i % 2 == 0:
            yield i

def odd_numbers(n):
    for i in range(n):
        if i % 2 != 0:
            yield i


def all_numbers(n):
    yield from even_numbers(n)
    yield from odd_numbers(n)


for number in all_numbers(10):
    print(number)

In the example above, we have three generators: even_numbers, odd_numbers, and all_numbers. The all_numbers generator uses the yield from keyword to delegate the yield to the even_numbers and odd_numbers generators.

Note: If even_numbers runs forever, then all_numbers will never execute the odd_numbers generator.

If you need fine control over the execution of the generators, you can try using zip and iterating over both generators, or using the next method to manually iterate over the generators. However, if you just want to return the values from each generator, yield from is the way to go.

Without the yield from keyword, we would have to iterate over the even_numbers and odd_numbers generators, like this:

def all_numbers(n):
    for number in even_numbers(n):
        yield number
    for number in odd_numbers(n):
        yield number

The yield from keyword makes the code cleaner and easier to read.

And that’s it! Hope that helps! :)

Translations: