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
.
Just ran into this issue with
Awaitable
(which suffers from the same problem asCoroutine
). 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 containCoroutine
(orAwaitable
),mypy
doesn't actually appear to use the stdlibtyping
. Instead, when invoked it uses its own version of thetyping
module. So, as long as yourmypy
is up to date, it will know abouttyping.Coroutine
(andtyping.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: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, excepts/Coroutine/Awaitable
.The library
typing
was not official on 3.5, but became official on 3.6. So for older than 3.6 you need to install a specific library : Typing moduleFor 3.6 you need nothing because it became official