Course contentsShow
← Python
Lesson 652 of 1,06010. Advanced Language FeaturesFree lesson

Applying Runtime Protocol Checking with runtime_checkable

Use the runtime_checkable decorator to enable the use of isinstance and issubclass checks against protocols during the execution of your code.

In this lesson, you will learn how to enable isinstance and issubclass checks for your Protocol classes by using the @runtime_checkable decorator.

The Problem with Static Protocols

In Python, Protocols are primarily designed for static type checking. When you define a Protocol, the type checker uses it to ensure objects provide the expected interface. However, if you attempt to use a standard Protocol with isinstance(obj, MyProtocol), Python will raise a TypeError. This happens because standard Protocols are erased at runtime to keep performance high.

Enabling Runtime Checks

To bridge this gap, you can import runtime_checkable from the typing module and apply it as a decorator to your Protocol. This instructs Python to perform a structural check—verifying that the object actually possesses the attributes or methods defined in the Protocol—whenever you run an isinstance check.

Consider this example:

from typing import Protocol, runtime_checkable

@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> None:
        ...

class Circle:
    def draw(self) -> None:
        print("Drawing a circle")

# Without @runtime_checkable, this would raise a TypeError
my_shape = Circle()
if isinstance(my_shape, Drawable):
    my_shape.draw()

How It Works

When you mark a Protocol as @runtime_checkable, the isinstance check performs a structural inspection by checking the object's __dict__ or calling hasattr for the required members.

This is incredibly useful when you are dealing with objects of unknown origin (like those coming from a plugin or a dynamic configuration) and you need to confirm they support a specific interface before calling methods on them. It effectively formalizes the "duck typing" philosophy by allowing you to verify an object's capabilities explicitly at runtime without requiring an explicit inheritance hierarchy.

Key Takeaway: Use the @runtime_checkable decorator on your Protocol classes when you need to perform isinstance or issubclass checks at runtime to verify that an object structurally conforms to your defined interface.