Passing asyncio loop by argument or using default asyncio loop

坚强是说给别人听的谎言 提交于 2019-12-20 09:37:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/40340493/passing-asyncio-loop-by-argument-or-using-default-asyncio-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!