Python text input module skips Coroutine class in python 3.5

I am trying to write code that uses the Coroutine class as described in the print documentation .

It looks like it is available in python 3.5 , but when I print it for import, it throws ImportError me:

 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. Is this class not available in python 3.5 ? If not, then why does it appear in the documentation (specifically on python 3.5)? I tried to launch it using python 3.5.2 .

+5
source share
2 answers

The typing library was not official at 3.5, but became official at 3.6. Thus, for more than 3.6 you need to install a specific library: Input module
For 3.6 you do not need anything because it has become official

+1
source

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

We rely on the fact that while Python 3.5 stdlib typing does not contain Coroutine (or Awaitable ), mypy is not actually used to use stdlib typing . Instead, when invoked, it uses its own version of the typing module. So, while your mypy updated, it will know about typing.Coroutine (and typing.Awaitable ). Therefore, the only thing you need to do is fake the existence of these types for the runtime (where you cannot import them). This can be done like this:

 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 that, use Coroutine[A, B, C] as usual. Your code will look right, and at runtime you will not have problems due to the lack of 3.5 stdlib.

This does not allow you to do any RTTI, but AFAIK, that part of the PEP that landed experimentally at 3.6 (or possibly 3.7) anyway.

For Awaitable this is the same workaround except for s/Coroutine/Awaitable .

0
source

Source: https://habr.com/ru/post/1269025/


All Articles