What is Yield for?

Asked

Viewed 15,296 times

29

I’ve been writing some for some time scripts with Python, in some tutorials I am sometimes presented with the yield, that normally arises in repeat structures commonly while. What is it for? And how to use?

3 answers

28


Python has its own specifics but essentially all languages work the same. It creates a Generator, that is, it creates a list of data that is being consumed on demand. In general it is used to give better abstractions to the code. Everything you do with it, you can do without it in a very similar way, but exposing the data generation mechanism.

It returns a value holding the state it left behind. When it runs again it continues where it left off. It controls the state of an enumerator between function executions.

def impar(elems):
    for i in elems:
        if i % 2:
            yield i

for x in impar(range(1000)):

Source.

This code will print all odd numbers from 0 to 1000. It will call the method 500 times, each time will bring an odd number. The compiler/library will mount the internal structure to know what number it is on each call.

Of course it has a hidden variable that survives beyond the function’s internal environment. So this i does not start again on each function call. Note that you can call the function impar() without knowing how she makes the selection internally.

This example is simple and obvious, but think of more complex things. You abstract better. You say you will call a method that filters the odd ones for you. It doesn’t matter how. What you will do with the generated information is your problem. The function with the yield has a unique responsibility to generate information.

Another example:

def numeros():
    yield 1
    yield 2
    yield 3

print numeros()
print numeros()
print numeros()

This will print 1, 2 and 3.

Behold explanations in C# and PHP.

  • In a nutshell, the yield "eats" some of the values contained in a repeating structure, without causing interruptions, is this ?

  • 3

    It’s the other way around. The idea of eating, it’s good, it picks up one seed at a time. But it’s interrupted. The yield is a return, It closes the execution, it stops. But the seed bag is still there the way you left it. You don’t get a new bag every time you call, as it would in the return. It does not need to be a repeating structure, but it needs to have a data sequence.

  • In this case, controlled interruptions ?

  • 1

    Yes, totally. I edited to give a different example.

  • I understand, thank you for your time.

  • For being a didactic example it would be more interesting to simplify the syntax to the maximum. When passing the constructor to for for instead of odd(range(1000)) use odd(1000), ie the "range" goes into def, which confuses less.

  • Worth seeing this one video to further complement the answer

Show 2 more comments

6

Complementing Maniero’s response, some features of the Yield:

Yield Python is used whenever you need to define a generator function of something. You can’t use it Yield out of a Generator Function.

When you use the instruction Yield within a function, it transforms into a generating function.

Generating function is a function that returns more than one value - returns a series of values.

A common use is within loops, for example:

for value in simpleGeneratorFun():  
     print(value)  

And the statement of our generating function would be something like this:

def simpleGeneratorFun():
    for i in range (1, 4):
        yield i

Whenever the instruction Yield occurs within the generating function, the program pauses the execution and returns the value to the caller. In the above example, it returns a value in the for.

The Yield retains the state of the function where it is paused (by returning the value).

Next time, when a caller calls the generating function - in our case, the for - the body of the function will execute the instruction from where it was paused, instead of executing the first instruction.

You can call the generating function, as long as it has not reached its last statement, ie the first time you call simpleGeneratorFun() it will return 1. On Monday it will return 2, until it arrives in 4.

Summarized, a little edited for better understanding and translated from:
https://www.csestack.org/python-yield-vs-return-explained-detail-examples/

-1

Yield is part of the python iterator protocol, it avoids you having to create the iterable element effectively, making your code more scalable, saving memory mainly. As an example, imagine that you have a list of integer numbers and want a loop not by those numbers but by their square. A natural solution would be to create a list by iterating for each element of the first and allocating at each position the square of the value. In this case, you will have a new list created by allocating memory that can easily explode depending on the number of elements in your source list. In the case of GENERATOR FUNCTIONS (definition of functions that use Yield and not Return), they return a GENERATOR OBJECT that in the background is an iterator. This iterator can save the current state of the object by accessing the next one from the previous one, so you do not need at any time to allocate your entire list. Values are accessed on demand in a loop or via build-in Function next(). When using Yield its function works like a corrosion, the first time it is called, the function starts running from its first line, when arriving at Yield it returns the value defined when called again it starts to rotate from the next line to Yield so it can function as an iterator. Another way to create interactor’s in python is through object orientation using the Dunder methods iter and next.

I will put the source of a very good book on this topic.

Powerful Python: The Most Impactful Patterns, Features and Development Strategies Modern Python Provides

Browser other questions tagged

You are not signed in. Login or sign up in order to post.