Sub topic 8
Runtime checks with @runtime_checkable and their limits
This chapter assumes you can write Python classes and type hints, and that you have defined a basic Protocol as covered earlier in this tutorial. A type checker such as mypy or pyright verifies protocols before the program runs. Sometimes you also want to ask the question while the program is running. This chapter shows how, and where the answer stops being reliable.
Why protocols need a decorator for isinstance
A plain protocol exists for static checking only. If you call isinstance with it, Python raises a TypeError.
from typing import Protocol
class Closeable(Protocol):
def close(self) -> None: ...
try:
isinstance(open(__file__), Closeable)
except TypeError as error:
print(error)The error says the protocol is not runtime-checkable. Python makes you opt in, because a runtime check is much weaker than a static one.
Opting in with @runtime_checkable
Add the @runtime_checkable decorator from typing to the protocol class. After that, isinstance works with it.
import io
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
print(isinstance(io.StringIO(), Closeable)) # True
print(isinstance(42, Closeable)) # Falseio.StringIO never inherits from Closeable. It passes because it has a close attribute.
What the runtime check actually does
At runtime, isinstance checks only that every member named in the protocol exists on the object. It does not check anything else.
- It does not compare parameter lists or parameter types.
- It does not check return types.
- It does not check whether an attribute is a method or a plain value.
The next example shows the gap. The class below has a close method that requires an argument, so the protocol's close() call would fail. The runtime check still passes.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class Broken:
def close(self, force: bool) -> int:
return 1
print(isinstance(Broken(), Closeable)) # True, despite the wrong signatureA static checker would reject Broken for this protocol. isinstance accepts it.
Limits and common errors
Data protocols and issubclass
issubclass works only with protocols that contain methods alone. If the protocol declares a data member such as an attribute or property, issubclass raises a TypeError. isinstance still works with such protocols, but it only looks for the attribute name on the instance.
Attributes set in `__init__`
For isinstance, an instance attribute is found once it has been assigned. The check therefore depends on the object's state at that moment, which can surprise you with objects that are only partly initialised.
A member that is None
A class can set a protocol method name to None to signal that it does not support it. Python's own protocols use this for __hash__. Treat a member that exists but is None with care, because a name-only check can be misled.
Cost
Runtime protocol checks are slower than ordinary isinstance checks against a class. Avoid them in tight loops.
When a runtime check is a good fit
Use @runtime_checkable when you need to branch on capabilities, for example to accept either a single object or something with a richer interface.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Flushable(Protocol):
def flush(self) -> None: ...
def finish(stream: object) -> None:
if isinstance(stream, Flushable):
stream.flush()
print("done")
import io
finish(io.StringIO())
finish(object())Here the check is a cheap guard, and the branch only calls a method with no arguments. Keep your protocols small so that the name-only check is close to the full contract.
Exercise
A class defines def close(self, force: bool) -> int. The protocol Closeable is decorated with @runtime_checkable and declares def close(self) -> None. What does isinstance(obj, Closeable) return, and what would a static type checker say about passing obj to a function that expects Closeable?
Show answer
isinstance returns True, because it checks only that a member named close exists. A static type checker reports an error, because the signature is not compatible: it requires an extra argument and returns int instead of None.
Exercise
Why does issubclass(SomeClass, Named) raise a TypeError when Named is a runtime-checkable protocol with a name property?
Show answer
issubclass is supported only for protocols whose members are all methods. A protocol with a data member such as a property cannot be checked against a class alone, so Python raises TypeError.