简体   繁体   English

asyncio 事件循环的独立于平台的 mypy 类型注释是什么?

[英]What is the platform-independent mypy type annotation for asyncio event loop?

I want to write mypy -typed code that uses asyncio and works on multiple platforms.我想编写使用mypy并在多个平台上工作的asyncio类型的代码。 Specifically, I often have classes and methods that explicitly bind to an event loop.具体来说,我经常有显式绑定到事件循环的类和方法。 I want to provide a type annotation for the event loop.我想为事件循环提供类型注释。

When I check the type of the asyncio event loop on Linux, I get:当我检查asyncio上的异步事件循环的类型时,我得到:

>>> import asyncio
>>> type(asyncio.get_event_loop())
<class 'asyncio.unix_events._UnixSelectorEventLoop'>

This type is clearly tied to the Unix/Linux platform.这种类型显然与 Unix/Linux 平台相关。

Now, I can write code that explicitly types the event loop with this type:现在,我可以编写代码来显式指定事件循环的类型:

import asyncio
from asyncio.unix_events import _UnixSelectorEventLoop  # type: ignore
def func(loop: _UnixSelectorEventLoop) -> None:
    print(loop)
func(asyncio.get_event_loop())

But you'll notice that I have to include a # type: ignore tag on the the _UnixSelectorEventLoop import because asyncio.unix_events has no type stubs.但是您会注意到我必须在_UnixSelectorEventLoop导入中包含一个# type: ignore标记,因为asyncio.unix_events没有类型存根。 I am also hesitant to import a method that is intended to be private, as indicated by the the underscore at the start of the class name.我也犹豫是否要导入一个旨在私有的方法,如 class 名称开头的下划线所示。

As an alternative, I can use AbstractEventLoop as the type:作为替代方案,我可以使用AbstractEventLoop作为类型:

import asyncio
def func(loop: asyncio.AbstractEventLoop) -> None:
    print(loop)
func(asyncio.get_event_loop())

And this passes a mypy type check successfully.这成功通过了 mypy 类型检查。 I am hesitant to use AbstractEventLoop as my type because it is an abstract type.我对使用AbstractEventLoop作为我的类型犹豫不决,因为它是一个抽象类型。

Is there an alternative type signature that works across platforms, does not require the use of abstract class definitions, and passes mypy type checking?是否有跨平台工作的替代类型签名,不需要使用抽象 class 定义,并通过 mypy 类型检查?

If you look at the CPython source code, AbstractEventLoop is actually the correct, OS independent definition of the event loop.如果您查看 CPython 源代码, AbstractEventLoop实际上是事件循环的正确的、独立于操作系统的定义。

You can find the source code in question here .您可以在此处找到有问题的源代码。

So I think, you are actually right, and should feel good about this type-hint choice.所以我认为,您实际上是对的,并且应该对这种类型提示选择感到满意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM