python - "Protocols cannot be used with isinstance()"- 为什么不呢?

标签 python python-3.x isinstance

新的 typing 模块包含多个对象,名称如“SupportsInt”(-Float、-Bytes 等)。 the documentation page for the module 上的名称和描述,可能会被解读为建议您可以测试对象是否属于“支持 __int__()”的类型。但是,如果您尝试使用 isinstance(),它会给出一个响应,明确表明您不应该这样做:

>>> isinstance(5, typing.SupportsInt)
(Traceback omitted)
TypeError: Protocols cannot be used with isinstance().

另一方面,您可以使用 issubclass():

>>> issubclass((5).__class__, typing.SupportsInt)
True
>>> issubclass(type(5), typing.SupportsInt)
True

在此上下文中什么是“协议(protocol)”?为什么它不允许以这种方式使用 isinstance()

最佳答案

如果你遇到这个问题想绕过错误(就像我做的那样),解决方案是用 @runtime_checkable 装饰协议(protocol)类:

from typing import Protocol, runtime_checkable

@runtime_checkable
class StorageProtocol(Protocol):
    ...

@typing.runtime_checkable

Mark a protocol class as a runtime protocol.

Such a protocol can be used with isinstance() and issubclass().

storage = ...  # get something that must implement StorageProtocol
if not isinstance(storage, StorageProtocol):
    raise RuntimeError(...)

关于python - "Protocols cannot be used with isinstance()"- 为什么不呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34844514/

相关文章:

python - 为什么 Anaconda 发行版不能在 Windows 10 64 位上运行?

python-3.x - 音乐无法从文件中播放,但在IDLE中可以正常播放

python - 如何从 Keras.layers 实现 Merge

python - Python 中 isinstance() 的否定形式

python - 如何在 Visual Studio Code 中的当前文件目录中运行 python interactive?

python - 如何迭代数据帧行,以更Pythonic的方式替换匹配元组中的值?

python - 将多个变量断言为同一类型

python - 检查self是否是python中子类的实例

javascript - ajax 调用未在浏览器中显示任何内容

python - BeautifulSoup 在 Django 中没有得到任何输出