The yield from syntax establishes a direct connection between the caller and the sub-generator, allowing data to flow seamlessly between them. Unlike traditional for loops, which can only yield values, yield from provides a bidirectional channel. This is analogous to establishing a temporary connection between client sockets, enabling both receiving and sending of data.
def reader():
"Simulates reading data from a source"
for i in range(4):
yield f"By using yield from, we can iterate over the reader generator without manually handling the loop.
Example: Sending Data to a Coroutine
def writer():
"Simulates writing data to a destination"
while True:
w = (yield)
print(f">>> {w}")
writer_wrapper = writer_wrapper(writer())
for i in range(4):
wrap.send(i) # Output: >>> 0, >>> 1, >>> 2, >>> 3
In this example, the yield from syntax allows the wrapper function to send data to the writer() coroutine, establishing a direct data exchange.
Exception Handling
Yield from also handles error propagation transparently. If the sub-generator encounters an exception, it can be either re-raised by the caller or handled within the sub-generator.
Example: Exception Handling with SpamException
class SpamException(Exception):
pass
def writer():
while True:
try:
w = (yield)
except SpamException:
print("***")
else:
print(f">>> {w}")
writer_wrapper = writer_wrapper(writer())
# Raising an exception within the wrapper
wrap.throw(SpamException)
# Expected Output: ***
Yield from ensures that exceptions are propagated smoothly, without the need for manual exception handling in the wrapper function.
Conclusion
Yield from is a powerful syntax that simplifies the implementation of bidirectional data exchange between caller and sub-generators, handling exceptions seamlessly. It provides a transparent and efficient way to communicate between these components, making it a valuable tool for dealing with complex data processing scenarios in Python 3.3 and later.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3