The obvious solution to the problem is to use issubclass
, but this raises TypeError
(using Python 3.6.7), e.g.
JavaScript
x
22
22
1
>>> from typing_extensions import Protocol
2
>>> class ProtoSubclass(Protocol):
3
pass
4
5
>>> issubclass(ProtoSubclass, Protocol)
6
Traceback (most recent call last):
7
File "<stdin>", line 1, in <module>
8
File "/opt/conda/envs/airflow/lib/python3.6/site-packages/typing_extensions.py", line 1265, in __subclasscheck__
9
raise TypeError("Instance and class checks can only be used with"
10
TypeError: Instance and class checks can only be used with @runtime protocols
11
>>> from typing_extensions import runtime
12
>>> @runtime
13
class ProtoSubclass(Protocol):
14
pass
15
16
>>> issubclass(ProtoSubclass, Protocol)
17
Traceback (most recent call last):
18
File "<stdin>", line 1, in <module>
19
File "/opt/conda/envs/airflow/lib/python3.6/site-packages/typing_extensions.py", line 1265, in __subclasscheck__
20
raise TypeError("Instance and class checks can only be used with"
21
TypeError: Instance and class checks can only be used with @runtime protocols
22
Advertisement
Answer
For more on the topic of python Protocols
, see
In Python 3.6.7, one way to solve this is to use the @runtime_checkable
decorator:
JavaScript
1
18
18
1
>>> from typing_extensions import Protocol
2
>>> from typing_extensions import runtime_checkable
3
4
>>> @runtime_checkable
5
class CustomProtocol(Protocol):
6
def custom(self):
7
8
9
10
>>> @runtime_checkable
11
class ExtendedCustomProtocol(CustomProtocol, Protocol):
12
def extended(self):
13
14
15
16
>>> issubclass(ExtendedCustomProtocol, CustomProtocol)
17
True
18