新的 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()
andissubclass()
.
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/