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

Managing Protocol Inheritance and Composition

Compose complex interfaces by inheriting from multiple protocols to create granular, reusable structural requirements for your application components.

In this lesson, you will learn how to build sophisticated interface requirements by composing multiple smaller Protocols into a single, cohesive structural contract.

Why Compose Protocols?

In complex applications, creating one "God Protocol" that defines every method a class needs is brittle and violates the Interface Segregation Principle. Instead, Python allows you to define granular Protocols for specific behaviors—like Readable, Writable, or Serializable—and combine them through inheritance. This allows your components to stay flexible, reusable, and decoupled.

Composing Interfaces

When you inherit from multiple protocols, a class satisfies the child protocol only if it implements all the requirements defined in the entire inheritance chain. This is a powerful way to define "composed" expectations for your dependencies.

from typing import Protocol

class Reader(Protocol):
    def read(self) -> str: ...

class Writer(Protocol):
    def write(self, data: str) -> None: ...

# Composing interfaces through multiple inheritance
class ReadWriteDevice(Reader, Writer, Protocol):
    """A device that must support both reading and writing."""
    def close(self) -> None: ...

class FileManager:
    def read(self) -> str: return "data"
    def write(self, data: str) -> None: pass
    def close(self) -> None: pass

def process_device(device: ReadWriteDevice):
    # This function now expects all three methods defined in the hierarchy
    device.read()
    device.write("test")
    device.close()

The Power of Granularity

By breaking your requirements into smaller units, you can write functions that accept only the specific interface they need. A function designed to print logs might accept only a Writer, whereas a data sync utility would require a ReadWriteDevice.

Because Python uses structural subtyping, you don’t need to explicitly inherit from these protocols in your classes. As long as your object provides the necessary methods, it will satisfy the composed protocol. This approach keeps your type-checking strict while allowing your actual implementations to remain lightweight and decoupled from formal class hierarchies. You are essentially building a custom "vocabulary" of behaviors that your architecture can mix and match.

Key Takeaway: Use multiple inheritance to combine simple, single-purpose Protocols into robust, granular interfaces that clearly define exactly what behavior your components require.