Define Structural Interfaces with Protocol
Core idea
A protocol describes the operations a value must support, without requiring inheritance from the protocol. A checker compares the declared member signatures. @runtime_checkable permits limited instance checks for member presence, not signature or type validation.
from typing import Protocolclass Exporter(Protocol): def export(self)->str: ...class Report: def export(self)->str: return 'ready'def send(x:Exporter)->str: return x.export()print(send(Report()))Report fulfills the required operation without inheritance.
Check presence only
from typing import Protocol, runtime_checkable@runtime_checkableclass Flushable(Protocol): def flush(self)->None: ...class Buffer: def flush(self): print('flushed')print(isinstance(Buffer(),Flushable))Buffer().flush()The runtime test sees flush; the actual method performs the work.
Common mistake
Do not interpret a successful runtime protocol check as proof of a compatible signature. Use static checking and behavioral tests.
Practice
Add a second exporter that returns a string, and a deliberately incompatible one returning an integer; compare checker results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Protocol and structural typing
Check your understanding of protocol and structural typing.
What is printed?
from typing import Protocol,runtime_checkable@runtime_checkableclass P(Protocol): def run(self)->None: ...print(isinstance(object(),P))What is printed?
class Writer: def write(self): return 3def use(w): return w.write()print(use(Writer()))Must a compatible class inherit a protocol?
What is checked by runtime_checkable?