Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python typing module missing the Coroutine class in python 3.5

I am trying to write code which uses the Coroutine class, as described in the typing documentation.

It's look like it's available in python 3.5, but when I am typing to import it throws me an ImportError:

In [1]: from typing import Coroutine

ImportError: cannot import name 'Coroutine'

Then, I tried to run the code in Python 3.6 and it worked fine. Does this class not available in python 3.5? If not, why it's appear in the documentation (of python 3.5 in particular)? I tried to run it with python 3.5.2.

like image 626
Yuval Pruss Avatar asked Jun 20 '17 10:06

Yuval Pruss


1 Answers

Just ran into this issue with Awaitable (which suffers from the same problem as Coroutine). It's missing from the stdlib and there seems to be no easy way to just pull it from pypi. If you're tied into Python 3.5, then this workaround may work for you:

We rely on the fact that despite the Python 3.5 stdlib typing does not contain Coroutine (or Awaitable), mypy doesn't actually appear to use the stdlib typing. Instead, when invoked it uses its own version of the typing module. So, as long as your mypy is up to date, it will know about typing.Coroutine (and typing.Awaitable). So the only thing you need to do is fake the existence of these types for runtime (where you can't import them). This can be achieved like so:

from typing import Any, TYPE_CHECKING
try:
    from typing import Coroutine
except ImportError:
    class _Coroutine:
        # Fake, so you can do Coroutine[foo, bar, baz]
        # You could assert the proper number of items are in the slice,
        # but that seems like overkill, given that mypy will check this
        # and at runtime you probably no longer care
        def __getitem__(self, index: Any) -> None:
            pass

    if not TYPE_CHECKING:
        Coroutine = _Coroutine()

After this, use Coroutine[A, B, C] as normal. Your code will typecheck properly and at runtime you won't have any issues due to it being missing from the 3.5 stdlib.

This does prevent you from doing any RTTI, but AFAIK that's part of a PEP that landed experimentally in 3.6 (or maybe 3.7) anyways.

For Awaitable, it's the same workaround, except s/Coroutine/Awaitable.

like image 132
Bailey Parker Avatar answered Oct 06 '22 00:10

Bailey Parker