Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing asyncio loop by argument or using default asyncio loop

Tags:

I'm using asyncio in my application and i'm a litte bit confused about passing the event loop as argument.

You've three possibilities when writing a function/method using the event loop:

  • Pass the asyncio event loop as argument
  • Don't use an argument for the event loop and use asyncio.get_event_loop()
  • Make it optional to pass the event loop as argument. If it is not passed, use asyncio.get_event_loop()

It seems that the last case is used most of the time but even in the asyncio api the usage is inconsistent. As I don't indent to use two seperated event loops what speaks against just using asyncio.get_event_loop() where needed?

What's the best way to go?

like image 308
Günther Jena Avatar asked Oct 31 '16 10:10

Günther Jena


People also ask

How does the Asyncio event loop work?

Deep inside asyncio, we have an event loop. An event loop of tasks. The event loop's job is to call tasks every time they are ready and coordinate all that effort into one single working machine. The IO part of the event loop is built upon a single crucial function called select .

How many times should Asyncio run () be called?

It should be used as a main entry point for asyncio programs, and should ideally only be called once. New in version 3.7.

What is Loop Run_in_executor?

run_in_executor is used to manage threads from within an event loop. To this end, it needs to wrap the thread into a Future, which needs to be assigned to an event loop (in one way or another). The reason the method is stored directly in a loop object is probably historical.

How do I stop Asyncio from looping events?

Run an asyncio Event Loop run_until_complete(<some Future object>) – this function runs a given Future object, usually a coroutine defined by the async / await pattern, until it's complete. run_forever() – this function runs the loop forever. stop() – the stop function stops a running loop.


1 Answers

A good (as in praised by Guido van Rossum) blog post discussing this is Some thoughts on asynchronous API design in a post-async/await world. With a follow up discussion from python core developers here.

TLDR;

If you're only using one event loop, it doesn't matter.

If you're managing multiple loops, and have python >= 3.6 it mostly doesn't matter: Do not use argument and use asyncio.get_event_loop() where needed, it will give you the correct loop.

like image 101
ttyridal Avatar answered Oct 04 '22 14:10

ttyridal