Sub topic 8
Runtime checks with @runtime_checkable and their limits
This chapter assumes you can write Python classes and functions, read basic type hints, and define a simple Protocol. It also assumes you know that a static type checker such as mypy or pyright analyzes code without running it. Here you will see how a protocol can take part in isinstance checks while the program runs, and where that mechanism stops being reliable.
Protocols are invisible at runtime by default
A protocol exists mainly for the type checker. Python itself does not treat it as a membership test. If you pass an ordinary protocol to isinstance, Python refuses.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
try:
isinstance(42, SupportsClose)
except TypeError as exc:
print(exc)The output is Instance and class checks can only be used with @runtime_checkable protocols. The refusal is deliberate. The authors of the typing system wanted you to opt in, because a runtime check cannot match what the static check does, as the rest of this chapter shows.
Opting in with @runtime_checkable
Adding the @runtime_checkable decorator makes the protocol usable with isinstance and, under conditions covered below, issubclass.
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)) # FalseNo inheritance is involved. io.StringIO has a close attribute, so it passes. The integer has none, so it fails.
A common use is narrowing a loosely typed value so that both Python and the type checker know what you can do with it:
import io
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
def shutdown_all(items: list[object]) -> None:
for item in items:
if isinstance(item, Closeable):
item.close()
print("closed", type(item).__name__)
else:
print("skipped", type(item).__name__)
shutdown_all([io.StringIO(), 42, io.BytesIO()])Inside the if branch, mypy and pyright treat item as Closeable, so the close() call type-checks.
What isinstance actually checks
The check is shallow. For each member the protocol declares, Python asks whether the object has an attribute of that name. It does not look at parameters, return types, or the type of an attribute's value.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class BadClose:
def close(self, force: bool, timeout: float) -> None:
pass
class NotAMethod:
close = "not callable"
print(isinstance(BadClose(), Closeable)) # True
print(isinstance(NotAMethod(), Closeable)) # TrueBoth objects pass, although calling item.close() on either would fail. BadClose.close requires two arguments. NotAMethod.close is a string. A static checker would reject both classes where a Closeable is required. The runtime check cannot.
| Question | Static checker | `isinstance` with `@runtime_checkable` |
|---|---|---|
| Does the member name exist? | Yes | Yes |
| Do parameter types and counts match? | Yes | No |
| Does the return type match? | Yes | No |
| Is a method really callable? | Yes | No |
| Does a read-only property match a plain attribute? | Yes | Only by name |
How the check works, and version differences
On Python 3.12 and later, isinstance against a runtime-checkable protocol looks up members with inspect.getattr_static. That function finds attributes without running descriptors, so a property is not evaluated and __getattr__ is not called. On older versions the check used hasattr, which could run property code and could behave differently when a property raised an exception. If your code must support several Python versions, avoid depending on this difference. Keep the members of runtime-checked protocols simple.
The decision flow is the same in every version:
Data members and issubclass
A protocol can declare plain attributes as well as methods. isinstance works with these, because an instance attribute assigned in __init__ is found on the instance. issubclass does not.
from typing import Protocol, runtime_checkable
@runtime_checkable
class HasName(Protocol):
name: str
class User:
def __init__(self, name: str) -> None:
self.name = name
class Anonymous:
pass
print(isinstance(User("Ada"), HasName)) # True
print(isinstance(Anonymous(), HasName)) # False
try:
issubclass(User, HasName)
except TypeError:
print("TypeError: issubclass needs a protocol with only methods")issubclass receives a class, not an instance. An attribute created inside __init__ does not exist on the class, so the answer would be unreliable. Python raises TypeError for any protocol that has non-method members. A protocol with only methods supports both isinstance and issubclass.
Note also that an annotation alone, such as name: str in a class body, does not create an attribute. A class that declares name: str but never assigns it fails the check for the same reason Anonymous does.
Callback protocols and generic protocols
Both kinds of protocol can be decorated, but the check says less than you might expect.
A callback protocol declares __call__. The runtime check only confirms that the object has a __call__ attribute, so any callable passes, whatever its parameters:
from typing import Protocol, runtime_checkable
@runtime_checkable
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
def log_handler(event: str, *, retries: int = 0) -> bool:
return True
print(isinstance(log_handler, Handler)) # True
print(isinstance(len, Handler)) # True, wrong signature is not detected
print(isinstance(42, Handler)) # FalseFor a generic protocol, you can check against the bare protocol, but not against a parameterized one:
from typing import Protocol, TypeVar, runtime_checkable
T_co = TypeVar("T_co", covariant=True)
@runtime_checkable
class Source(Protocol[T_co]):
def get(self) -> T_co: ...
class IntSource:
def get(self) -> int:
return 7
print(isinstance(IntSource(), Source)) # True
try:
isinstance(IntSource(), Source[int])
except TypeError:
print("TypeError: subscripted generics cannot be used in isinstance")Type arguments are erased at runtime, so there is nothing to compare int against. The type checker handles the Source[int] question, and the runtime handles only the member names.
Costs and pitfalls
- Speed. A protocol check inspects every member by name, each time. It is noticeably slower than
isinstanceagainst an ordinary class or an ABC, which can be answered from the class hierarchy. Avoid it in tight loops. - Large protocols. The more members a protocol declares, the more lookups each check performs. A larger protocol also makes a false positive harder to spot, because a check that passes tells you less than it seems to.
- Attributes absent until later. If an object assigns an attribute only after construction, the same object can fail the check early and pass it later.
- Tooling. Type checkers report an error if you use
isinstancewith a protocol that is not decorated. The decorator is needed for both the runtime and the static side. - Subclass behavior. A class that explicitly subclasses a runtime-checkable protocol is a registered subtype in the usual nominal sense. Its
isinstanceresult is True without a member lookup. An explicit subclass that forgets to implement a non-abstract member still passes, because protocol members with a body...are inherited.
Summary of the limits
- Without
@runtime_checkable,isinstanceandissubclassraiseTypeError. - With it, only member names are checked, never signatures, return types, or attribute value types.
issubclassworks only for protocols whose members are all methods.- Parameterized generic protocols cannot be used with
isinstance. - A callback protocol check accepts any callable.
- Details of attribute lookup changed in Python 3.12.
Exercise
The class below has a close method that requires two arguments. Given the Closeable protocol decorated with @runtime_checkable and declaring def close(self) -> None: ..., what does isinstance(Worker(), Closeable) return, and would a static type checker accept Worker() where a Closeable is required?
class Worker:
def close(self, force: bool, timeout: float) -> None:
pass
Show answer
It returns True, because isinstance only checks that an attribute named close exists. A static type checker rejects Worker() as a Closeable, because the signature requires two extra arguments that the protocol's close(self) -> None does not supply.
Exercise
You have a protocol HasName that declares the attribute name: str, decorated with @runtime_checkable. Which of these calls works, and which raises TypeError: isinstance(User("Ada"), HasName) or issubclass(User, HasName)? Explain why.
Show answer
isinstance(User("Ada"), HasName) works and returns True when User.__init__ assigns self.name. issubclass(User, HasName) raises TypeError, because the protocol has a non-method member and the attribute set in __init__ does not exist on the class itself, so a class-level answer would be unreliable.
Exercise
Why does isinstance(IntSource(), Source[int]) raise TypeError even when Source is runtime checkable, and what would you use instead to confirm that IntSource.get returns an int?
Show answer
Type arguments such as int are erased at runtime, so Python has nothing to compare, and it rejects subscripted generics in isinstance. To confirm the return type, run a static type checker such as mypy or pyright over the code, or check the returned value yourself, for example with isinstance(source.get(), int).