For some time now I have written some basic scripts with Python, in some tutorials sometimes I get the yield
, which usually appears in repetition structures commonly while
. What is it for? And how to use?
For some time now I have written some basic scripts with Python, in some tutorials sometimes I get the yield
, which usually appears in repetition structures commonly while
. What is it for? And how to use?
Python has its own specificities, 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. It is generally used to give better code abstractions. Everything you do with it, you can do without it in a very similar way, but exposing the mechanism of data generation.
It returns a value holding the state where it left off. When it runs again it continues where it left off. It controls the state of an enumerator between runs of the function.
def impar(elems):
for i in elems:
if i % 2:
yield i
for x in impar(range(1000)):
Font .
This code will print all odd numbers from 0 to 1000. It will call the method 500 times, each time it will bring an odd number. The compiler will mount the internal structure to know what number it is in each call. It is obvious that it has a hidden variable that survives beyond the internal environment of the function. So this i
does not start again with each function call. Note that you can call the impar()
function without knowing how it does 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. No matter how. What you will do with the information generated is your problem. The function with yield
has sole responsibility for generating the information.
Another example:
def numeros():
yield 1
yield 2
yield 3
print numeros()
print numeros()
print numeros()
This will print 1, 2, and 3.
See explanations in C # and PHP .