Junior — Middle
What is the role of the yield keyword in Python besides implementing generators?
sobes.tech AI
Answer from AI
The keyword yield in Python is used not only for creating generators but also for implementing coroutines and subroutines. It allows a function to pause its execution and return an intermediate value, preserving its state to continue later from the same point.
Besides generators, yield is used for organizing lazy computations and stream processing, as well as in asynchronous programming (for example, in the old style of coroutines before the appearance of async/await).
An example of using yield for a simple coroutine:
def grep(pattern):
print(f"Looking for {pattern}")
while True:
line = (yield)
if pattern in line:
print(line)
search = grep("python")
next(search) # Start the coroutine
search.send("hello world")
search.send("python is great") # Will print: python is great
Here, yield is used to receive data from outside and process it as it arrives.