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:
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:
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
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.
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