Async Await: Understanding Python 3.5’s New Coroutine Syntax

I want to understand why they are being removed in Python 3.7.

Original In a nutshell, Python’s asyncio module is getting some major updates in version 3.7. One of these changes involves removing the ability to pass arguments to coroutine functions using the `loop` parameter. This change may seem confusing at first, but it actually simplifies things and makes your code more readable.

Previously, you could define a function as an asyncio coroutine by adding the `async def` syntax:

# Import the asyncio library
import asyncio

# Define a coroutine function using the `async def` syntax
async def my_coro():
    # do some stuff here...
    
    # Use the `await` keyword to call another coroutine function
    await other_coro()

# Create an event loop
loop = asyncio.get_event_loop()

# Run the coroutine function within the event loop
loop.run_until_complete(my_coro())

# Close the event loop
loop.close()

# The `loop` parameter is no longer needed when calling coroutine functions
# This simplifies the code and makes it more readable

In this example, we’re passing our custom loop object to the `other_coro()` function. However, in Python 3.7 and beyond, you can no longer pass arguments using the `loop` parameter when defining a coroutine function. Instead, you should create your own event loop instance outside of the coroutine functions:

# Import the asyncio library
import asyncio

# Define a coroutine function called my_coro
async def my_coro():
    # Do some stuff here...
    
    # Call the other_coro function
    await other_coro()

# Define a coroutine function called main
async def main():
    # Create an event loop instance
    loop = asyncio.get_event_loop()
    
    # Create a list of tasks to be executed concurrently
    tasks = [my_coro(), another_coro()]
    
    # Run the event loop until all tasks are completed
    await loop.run_until_complete(asyncio.gather(*tasks))

# Define a coroutine function called another_coro
async def another_coro():
    # Do some stuff here...

# Call the main function to start the program
asyncio.run(main())

# Note: In Python 3.7 and beyond, you can no longer pass arguments using the `loop` parameter when defining a coroutine function. Instead, you should create your own event loop instance outside of the coroutine functions.

In this updated example, we’re creating our own event loop instance using `asyncio.get_event_loop()`. We then create a list of tasks to run and pass them into the `asyncio.gather()` function. This allows us to easily manage multiple coroutine functions without having to worry about passing arguments to each one individually.

Overall, this change simplifies your code by removing unnecessary parameters and making it more readable. It also helps to reduce confusion around how event loops work in Python’s asyncio module.

SICORPS