无法从输入中导入协议

mad*_*mad 10 python python-3.x

我在 Windows 10 上全新安装了 Python 3.7-32。

我想尝试协议 python 方法,我接下来做:

文件 test_protocols.py 只有一行:

from typing import Protocol
Run Code Online (Sandbox Code Playgroud)

然后:

>python test_protocols.py
Run Code Online (Sandbox Code Playgroud)

我还有下一条需要解释的错误消息:

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)
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

也许我读错了 PEP-0544,但从我的角度来看,我做的和记录的一样。

yep*_*ons 7

截至 2019 年 1 月 20 日,PEP 544的状态为Draft。据我了解,它还没有在 CPython 中实现。

UPD:它应该从 Python 3.8 开始工作,请尝试更新。


Jas*_*sha 5

PEP 544实施部分,它说

mypy类型检查完全支持协议(模数已知的bug)。这包括处理所有内置协议,例如在 Iterable结构上。typing_extensionsPyPI 上的模块中提供了协议的运行时实现。

因此,在您的代码中,添加from typing_extensions import Protocol.


Thu*_*kwa 5

如果它在输入中不存在,请执行

pip install typing_extensions

from typing_extensions import Protocol
Run Code Online (Sandbox Code Playgroud)

根据操作系统和 Python 版本协议类可能在打字模块或打字扩展中。