Course contentsShow
← Python
Lesson 564 of 1,0609. Type Safety and Code QualityFree lesson

Defining Optional Protocols with Runtime Checking

You will use the runtime_checkable decorator to verify if objects implement specific protocols during execution, enabling safer dynamic dispatch.

Defining Optional Protocols with Runtime Checking

In this lesson, you’ll learn how to use the @runtime_checkable decorator to verify whether an object supports specific methods at runtime, allowing for safer dynamic behavior.

Why Runtime Checking?

While static type checkers like mypy catch many errors before you run your code, they rely on static analysis. Sometimes, you need to handle objects that might come from external libraries or dynamic sources where you aren't certain if they implement a specific feature. By using typing.Protocol combined with the @runtime_checkable decorator, you can inspect an object's capabilities while your program is actually running.

Implementing a Runtime-Checkable Protocol

To create a protocol that supports runtime inspection, import runtime_checkable and apply it as a decorator to your Protocol. Once decorated, you can use the built-in isinstance() function to check if an object implements the protocol's structure.

Consider a system where you want to trigger an optional "save" functionality only if an object supports it:

from typing import Protocol, runtime_checkable

@runtime_checkable
class Savable(Protocol):
    def save(self) -> None:
        ...

def process_data(item: object) -> None:
    # Use isinstance to perform a runtime check
    if isinstance(item, Savable):
        print("Saving item...")
        item.save()
    else:
        print("Item does not support saving; skipping.")

class DatabaseEntry:
    def save(self) -> None:
        print("Persisted to database.")

process_data(DatabaseEntry())  # Works!
process_data("Simple String")   # Safely skips

In this example, isinstance(item, Savable) checks if item has a save method. This allows you to perform structural subtyping dynamically. Unlike standard inheritance, the object doesn't need to explicitly inherit from Savable; it only needs to "look like" it satisfies the protocol definition.

This pattern is especially useful for plugin architectures or processing mixed collections of objects where you want to add optional functionality without forcing a rigid inheritance hierarchy.

Key Takeaway: The @runtime_checkable decorator enables isinstance() to verify structural compatibility at runtime, allowing you to safely invoke optional features on objects dynamically.