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?
asyncio.get_event_loop()returns an event loop, you can change it withasyncio.set_event_loop(). This willget/setthe event loop on the_event_loop_policy, a global variable in theasynciomodule. This is an easy way to share the eventloop in the application without a need to pass it around. So if you want to avoid having 2 separate event loops around, you may register the one event loop you've got in this global variable byset_event_loop().loop=asyncio.get_event_loop(). Then I'm setting up the asynchronous stuff (coroutines, async servers, ...) and my own functions where I've got this question about passing the loop argument. When everything is set up, I runloop.run_forever().