8. Coroutines

These snippets demonstrate the use of coroutines for multitasking and cooperative execution, including sending data, handling exceptions, and managing state. They also illustrate how coroutines can be integrated with asyncio for asynchronous programming.


1. Basic Coroutine Example

def simple_coroutine():
    print("Coroutine started")
    x = yield
    print(f"Received: {x}")

coro = simple_coroutine()
next(coro)         # Start the coroutine
coro.send(42)      # Output: Coroutine started \n Received: 42

2. Coroutine with Multiple yield Statements

def multi_yield_coroutine():
    print("Coroutine started")
    x = yield "First yield"
    print(f"Received: {x}")
    y = yield "Second yield"
    print(f"Received: {y}")

coro = multi_yield_coroutine()
print(next(coro))  # Output: Coroutine started \n First yield
print(coro.send(10))  # Output: Received: 10 \n Second yield
coro.send(20)         # Output: Received: 20

3. Coroutine for Accumulating Values


4. Coroutine for Data Filtering


5. Coroutine for String Processing


6. Coroutine with Exception Handling


7. Coroutine with Closing Behavior


8. Coroutine for Logging Messages


9. Coroutine for Producing Fibonacci Numbers


10. Coroutine with Asynchronous Behavior Using asyncio


Last updated