When to Use Yield Instead of Return in Python
Many Python developers use yield in their code without considering whether they really need to. This article explains when you it actually should be used.
Join the DZone community and get the full member experience.
Join For FreeLately, I’ve seen so many projects that are using yield
keyword in the structure, whether or not it was needed.
So I’ve decided to look into this a bit and wanted to share some information about it with you guys.
First things first.
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.
The yield statement suspends the function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it is left off. When resumed, the function continues the execution immediately after the last yield run. This allows its code to produce a series of values over time rather them computing them all at once and sending them back like a list.
Let’s see this with an example:
def simpleGeneratorFun():
yield 1
yield 2
yield 3
for value in simpleGeneratorFun():
print(value)
The output of this code will be:
1
2
3
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 thetry
clause of a try ... finally
construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the finally
block will ever get executed.
return
sends a specified value back to its caller, whereas yield
can produce a sequence of values.
We should use yield
when we want to iterate over a sequence but don’t want to store the entire sequence in memory.
yield
is used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield
keyword rather than return. If the body of a def
contains yield
, the function automatically becomes a generator function.
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
for num in nextSquare():
if num > 100:
break
print(num)
The output of this code will be:
1
4
9
16
25
36
49
64
81
100
And that's it!
Published at DZone with permission of Orcun Yilmaz. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments