通过参数传递 asyncio 循环或使用默认的 asyncio 循环 [英] Passing asyncio loop by argument or using default asyncio loop
问题描述
我在我的应用程序中使用了 asyncio,我对将 事件循环 作为参数传递有点困惑.
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:
- 将异步事件循环作为参数传递
- 不要为事件循环使用参数,而是使用
asyncio.get_event_loop()
- 将事件循环作为参数传递是可选的.如果没有通过,使用
asyncio.get_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()
似乎大部分时间都使用最后一种情况,但即使在 asyncio api 中,用法也不一致.由于我不缩进使用两个单独的事件循环,什么反对只在需要的地方使用 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?
最好的方法是什么?
推荐答案
讨论此问题的一篇很好的(如 Guido van Rossum 所称赞的)博客文章是 一些关于异步 API 设计的想法-async/await 世界.来自 python 核心开发人员的后续讨论此处.
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.
如果您正在管理多个循环,并且有 python >= 3.6,这几乎没有关系:不要使用参数并使用 asyncio.get_event_loop()
where需要,它会给你正确的循环.
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.
这篇关于通过参数传递 asyncio 循环或使用默认的 asyncio 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!