The yield statement suspends a function's execution and sends a value back to the caller.
Yield retains enough state to enable the function to resume where it left off.
When the function resumes, it 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 like a list.
def simpleGeneratorFun(): yield 1 yield 2 yield 3 for value in simpleGeneratorFun(): print(value) # 1 2 3
Useful when streaming data to client:
from django.http import StreamingHttpResponse def streaming_data(): # simulate a streaming of data for i in range(10): # yielding a chunked stream data yield f"data: {i}\n\n" response = StreamingHttpResponse(streaming_data(), content_type="text/event-stream") return response
return
vs yield
Return
sends a specified value back to its caller.
Yield
can produce a sequence of values.
Use yield when we want to iterate over a sequence, but don't want to store the entire sequence in memory.