mad
mad

Reputation: 1047

can not import Protocol from typing

I have fresh installed Python 3.7-32 on Windows 10.

I want to try Protocols python approach and I do next:

file test_protocols.py with only one row:

from typing import Protocol

then:

>python test_protocols.py

And I have next error message that is needed to be explained:

Traceback (most recent call last):
  File "test_protocols.py", line 1, in <module> 
    from typing import Protocol
ImportError: cannot import name 'Protocol' from 'typing' (C:\Programing\Python\Python37-32\lib\typing.py)

What do I do wrong?

Maybe I have read PEP-0544 wrong but from my point of view I do the same as it is documented.

Upvotes: 17

Views: 31885

Answers (3)

yeputons
yeputons

Reputation: 9238

As of January 20, 2019, PEP 544's status is Draft. As far as I understand, it's not implemented in CPython yet.

UPD: it should work since Python 3.8, try updating.

Upvotes: 13

Thulani Chivandikwa
Thulani Chivandikwa

Reputation: 3539

If it does not exist in typing do

pip install typing_extensions

from typing_extensions import Protocol

Depending upon OS and Python version Protocol class might be within typing module or in typing_extensions.

Upvotes: 17

Jasha
Jasha

Reputation: 7639

In the implementation section of PEP 544, it says

The mypy type checker fully supports protocols (modulo a few known bugs). This includes treating all the builtin protocols, such as Iterable structurally. The runtime implementation of protocols is available in typing_extensions module on PyPI.

Thus, in your code, add from typing_extensions import Protocol.

Upvotes: 7

Related Questions