In Practice, Leveraging the "yield from" Syntax in Python 3.3
The "yield from" syntax, introduced in Python 3.3, offers a significant enhancement to the capabilities of generators and coroutines. It establishes a bidirectional connection between a caller and a sub-generator, enabling seamless communication in both directions.
Use Cases for "yield from"
Reading Data from Generators:
<code class="python">def reader(): for i in range(4): yield '<< %s' % i def reader_wrapper(g): yield from g wrap = reader_wrapper(reader()) for i in wrap: print(i) # Result: # << 0 # << 1 # << 2 # << 3
Sending Data to Coroutines:
<code class="python">def writer(): while True: w = (yield) print('>> ', w) def writer_wrapper(coro): yield from coro w = writer() wrap = writer_wrapper(w) wrap.send(None) # Prime the coroutine for i in range(4): wrap.send(i) # Expected result: # >> 0 # >> 1 # >> 2 # >> 3</code>
Comparison to Micro-Threads
The yield from syntax shares some similarities with micro-threads in that it allows for suspending and resuming coroutines, creating a lightweight alternative to traditional threads. However, coroutines are more lightweight and have a lower memory overhead compared to micro-threads. They also run on the same thread, avoiding the issues associated with context switching in multi-threaded environments.
The above is the detailed content of What are the Use Cases and Benefits of Leveraging \'yield from\' Syntax in Python 3.3?. For more information, please follow other related articles on the PHP Chinese website!