Search code examples
pythonpython-asynciopython-typingmypy

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. 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:

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

This type is clearly tied to the Unix/Linux platform.

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. 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.

As an alternative, I can use AbstractEventLoop as the type:

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

And this passes a mypy type check successfully. I am hesitant to use AbstractEventLoop as my type because it is an abstract type.

Is there an alternative type signature that works across platforms, does not require the use of abstract class definitions, and passes mypy type checking?


Solution

  • If you look at the CPython source code, AbstractEventLoop is actually the correct, OS independent definition of the event loop.

    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.