简体   繁体   English

无法从输入中导入协议

[英]can not import Protocol from typing

I have fresh installed Python 3.7-32 on Windows 10.我在 Windows 10 上全新安装了 Python 3.7-32。

I want to try Protocols python approach and I do next:我想尝试 Protocols python 方法,我接下来做:

file test_protocols.py with only one row:文件 test_protocols.py 只有一行:

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.也许我读错了 PEP-0544,但从我的角度来看,我做的和记录的一样。

As of January 20, 2019, PEP 544 's status is Draft .截至 2019 年 1 月 20 日, PEP 544的状态为Draft As far as I understand, it's not implemented in CPython yet.据我了解,它还没有在 CPython 中实现。

UPD : it should work since Python 3.8, try updating. UPD :它应该从 Python 3.8 开始工作,请尝试更新。

In the implementation section of PEP 544 , it saysPEP 544实施部分,它说

The mypy type checker fully supports protocols (modulo a few known bugs). mypy类型检查器完全支持协议(以一些已知错误为模)。 This includes treating all the builtin protocols, such as Iterable structurally.这包括在结构上处理所有内置协议,例如Iterable The runtime implementation of protocols is available in typing_extensions module on PyPI. PyPI 上的typing_extensions模块中提供了协议的运行时实现。

Thus, in your code, add from typing_extensions import Protocol .因此,在您的代码中,添加from typing_extensions import Protocol

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.根据操作系统和 Python 版本协议类可能在打字模块或打字扩展中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM