Home > Enterprise >  What are the consequences (if any) of not running asyncio.set_event_loop(event_loop) after event_loo
What are the consequences (if any) of not running asyncio.set_event_loop(event_loop) after event_loo

Time:12-26

What are the consequences (if any) of not running asyncio.set_event_loop(event_loop) after event_loop = asyncio.new_event_loop? And if there are none then what's the purpose of asyncio.set_event_loop?

I have written some basic test code without set_event_loop to figure out what it does and I saw no change, so now I'm left wondering what the consequences of not using it are / what the purpose of it is.

The documentation says: "Set loop as the current event loop for the current OS thread."

But I'm not sure how that's useful.

Test code:

import asyncio

async def test1():
    count = 0
    while True:
        count  = 1
        await asyncio.sleep(1)
        print(count)

loop = asyncio.new_event_loop()
loop.run_until_complete(test1())

CodePudding user response:

As per your comment. Here is an example of when you might use asyncio.set_event_loop(event_loop):

import asyncio

# Create a new event loop
event_loop = asyncio.new_event_loop()

# Set the event loop as the default event loop for the current thread
asyncio.set_event_loop(event_loop)

# Run an asynchronous task using the event loop
async def my_task():
    print('Hello, world!')

event_loop.run_until_complete(my_task())

# Close the event loop
event_loop.close()

In this example, we create a new event loop using asyncio.new_event_loop(), and then set it as the default event loop for the current thread using asyncio.set_event_loop(event_loop). We can then run an asynchronous task using the event loop with event_loop.run_until_complete(my_task()).

The code in the original question is already the counter example. In fact i tend to use the code in the question more than that code in this answer (because it was the historical conventional method).

You might use asyncio.set_event_loop(event_loop) if you want to create a custom event loop with specific settings or behaviors, or if you want to use a different event loop than the default event loop provided by the asyncio module....

  • Related