"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What are the Use Cases and Benefits of Leveraging \"yield from\" Syntax in Python 3.3?

What are the Use Cases and Benefits of Leveraging \"yield from\" Syntax in Python 3.3?

Published on 2024-11-06
Browse:614

What are the Use Cases and Benefits of Leveraging \

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:

  • This use case mimics the functionality of a for loop, but with the added convenience of propagating exceptions. For example:
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:

  • This scenario involves creating a coroutine that accepts data sent to it and writes it to a specified location, like a file or a socket. For example:
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.

Release Statement This article is reprinted at: 1729681907 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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