gpt4 book ai didi

python - 如何测试 python 类型协议(protocol)是另一个协议(protocol)的子类?

转载 作者:行者123 更新时间:2023-12-01 06:40:50 25 4
gpt4 key购买 nike

该问题的明显解决方案是使用 issubclass,但这会引发 TypeError(使用 Python 3.6.7),例如

>>> from typing_extensions import Protocol
>>> class ProtoSubclass(Protocol):
... pass
...
>>> issubclass(ProtoSubclass, Protocol)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/conda/envs/airflow/lib/python3.6/site-packages/typing_extensions.py", line 1265, in __subclasscheck__
raise TypeError("Instance and class checks can only be used with"
TypeError: Instance and class checks can only be used with @runtime protocols
>>> from typing_extensions import runtime
>>> @runtime
... class ProtoSubclass(Protocol):
... pass
...
>>> issubclass(ProtoSubclass, Protocol)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/conda/envs/airflow/lib/python3.6/site-packages/typing_extensions.py", line 1265, in __subclasscheck__
raise TypeError("Instance and class checks can only be used with"
TypeError: Instance and class checks can only be used with @runtime protocols

最佳答案

所选答案虽然没有错误,但并没有反射(reflect)提供结构子类型的Protocol的实际使用。 Python 3 始终可以使用名义子类型。

from typing import Protocol, runtime_checkable

@runtime_checkable
class Closable(Protocol):
def close(self):
...

class AnyClass:
def close(self):
...

issubclass(AnyClass, Closable)
#> True

此外,仅在基类中需要 runtime_checkable,即使正在检查的类是 Protocol 子类。

class ExtendedProtocol(Closable, Protocol):
...

class AnotherProtocol(Protocol):
def close(self):
...

class NotAProtocol(Closable):
# just inherits the protocol's default implementation
...

issubclass(ExtendedProtocol, Closable)
#> True
issubclass(AnotherProtocol, Closable)
#> True
issubclass(NotAProtocol, Closable)
#> True

关于python - 如何测试 python 类型协议(protocol)是另一个协议(protocol)的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com