Introduction
If you’ve been writing some python code, you will definitely find yourself in need to writing functions to solve a task.
For example if I write the following code
def function_1(x : int) :
for i in range(10+1):
print(f'{x}*{i} = {x*i}')
return
It’s not difficult to understand the behavior of this function.
But what it let look at a slightly modified version of the above function
def function_2(x : int) :
for i in range(10+1):
yield(f'{x}*{i} = {x*i}')
It may not be obvious for you to understand the role of the keyword yield in function_2.
In function_1 our function is taking an integer, and produce a table of multiplication, from 0 to 10, by the given number.
5*0 = 0
5*1 = 5
5*2 = 10
5*3 = 15
5*4 = 20
5*5 = 25
5*6 = 30
5*7 = 35
5*8 = 40
5*9 = 45
5*10 = 50
In contrast the function_2 use a very special keyword yield that suspends the function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back (return).
Some fact about the yield keyword
The yield statement is only used when defining a generator function, and is only used in the body of the generator function. Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as a generator iterator, or more commonly, a generator. The body of the generator function is executed by calling the generator’s next() method repeatedly until it raises an exception.
When a yield statement is executed, the state of the generator is frozen and the value of expression_list is returned to next()’s caller. By ``frozen’’ we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time next() is invoked, the function can proceed exactly as if the yield statement were just another external call.
The yield statement is not allowed in the try clause of a try …
The picture below shows an output of the function_2
function_2 output
Advantages and Disadvantages of yield
Let conclude this short post by discussing some advantages and disadvantage of using the keyword yield in your program.
Advantages of yield:
- Since it stores the local variable states, the overhead of memory allocation is controlled.
- Since the old state is retained, flow doesn’t start from the beginning.
Disadvantages of yield:
- May became difficult to debug, when used without appropriate comments.
The associated notebook to the post can be find here.
Feel free to drop a note in the comment bellow. See you next time :)