Lesson · Type Hints & Static Typing
Protocols & Structural Typing
65 min readProtocols & Structural Typing
Protocols define structural interfaces for static type checkers. They bring explicit, checkable duck typing to APIs without forcing concrete classes into a shared inheritance tree.
Learning goals
- Define a
Protocolclass and explain how a checker decides an unrelated class satisfies it. - Distinguish structural subtyping from inheritance and give two unrelated classes that both fit one protocol.
- Explain what static duck typing checks at analysis time and what it leaves to runtime.
- Use
@runtime_checkableforisinstancechecks and state what such a check cannot see. - Choose between a protocol and an ABC based on whether classes can be modified and whether the contract must hold at runtime.
Mental model
A protocol is a description of the members a value must have, and the checker compares descriptions instead of class lineages. Nothing in the protocol executes; it gives the checker a name for the shape your function expects.
Mental model
read it top to bottom
checker question at every use site: "does the argument have the required members?" class Console has write(text) -> int yes → accepted class Recorder has write(text) -> int yes → accepted class Counter has no write no → rejected no inheritance anywhere: the comparison is member shapes, not family trees
Core idea
A protocol names the members a value must have, and the checker compares shapes instead of family trees: any class with matching attributes and method signatures fits, whether or not it has ever heard of the protocol. That is static duck typing, and its limits come from the checker's view, which reasons about declared signatures and cannot follow dynamic tricks. Use protocols to describe what a function needs from its arguments, and reach for an ABC when you also want shared implementation or enforcement at instantiation.
Protocol
Protocol defines a structural static interface. A class can satisfy the protocol without explicitly inheriting from it if its available members match the required shape.
Structural subtyping
Structural subtyping accepts a class for a type when its members match the required shape, with no inheritance relationship involved. A checker compares the available attributes and method signatures at the use site, so two unrelated classes can both satisfy the same protocol.
Static duck typing
Static duck typing applies the duck typing idea at check time: if an object provides the operations a protocol requires, the checker accepts it, and a wrong method signature is reported before the program runs. At runtime nothing is inspected, so the call behaves like any other duck-typed call.
Runtime-checkable protocols
A protocol decorated with @runtime_checkable can be used with isinstance and issubclass, which test only whether the required members exist. The check is shallow: methods are present or absent, and argument types and return types are never verified at runtime.
Protocols vs ABCs
A Protocol works structurally: a class satisfies it by having the right members and never needs to inherit from it. An ABC works nominally: a class must inherit (or be registered) to count, and abstract methods make an incomplete subclass fail at instantiation. Choose the protocol when classes must fit without modification, and the ABC when you want shared implementation or a contract enforced at runtime.
Walkthrough
class SupportsWrite(Protocol)declares one required member, awritemethod that takes a string and returns anint, and the protocol itself contains no implementation, so nothing runs from it.def send(writer: SupportsWrite, text: str)turns that shape into a parameter contract, andConsoleis accepted because itswritesignature matches, even though it never inherits fromSupportsWrite.Console.writeprints the text and returnslen(text), so the call also honors the stated return type; a class whosewritereturnsNonewould run fine but fail the checker's shape comparison.- Predict before running: what
send(Console(), "hello")prints, whethersendstill runs for a class whosewritereturnsNone, and what a checker says about that class.
Experiments to try
- Add a second class with a
writemethod that returnsNoneand pass it tosend; confirm the output still appears and note the checker complaint. - Decorate the protocol with
@runtime_checkableand runisinstance(Console(), SupportsWrite)andisinstance(42, SupportsWrite); explain what each result does and does not prove. - Rename
Console.writetoemitand pass aConsoletosend; read the checker error and the runtimeAttributeError, and explain why they surface at different moments. - Give
Consoleawritemethod with the wrong parameter list and callsend; show that the checker rejected the shape while runtime raisesTypeErrorat the call.
Common mistakes
- Expecting
isinstanceto work on a plain protocol: only a@runtime_checkableprotocol can be used there, and even then the check verifies member presence, not signatures. - Assuming a class must inherit from the protocol: structural subtyping makes the members the contract, so an unrelated third-party class can satisfy it untouched.
- Treating the protocol as runtime machinery: nothing installs defaults or validates calls, so the checker's acceptance does not make a call safe at runtime.
- Choosing an ABC purely as an interface marker: the ABC forces inheritance and blocks instantiation until the contract is complete, costs a protocol does not charge, so pick it only for shared behavior or runtime enforcement.
Practice: Easy
- Run the worked example, then add a
NullWriterclass withwrite(self, text: str) -> intreturning0; confirmsend(NullWriter(), "x")passes a checker even though the class never inherits fromSupportsWrite. - Add a
flush(self) -> Nonemethod to the protocol and show thatConsoleis rejected by a checker until it gains a matchingflush. - Rename
Console.writetoemitand pass aConsoletosend; describe the two failures, the checker error before running and theAttributeErrorat the call.
Practice: Medium
- Write
class SupportsClose(Protocol): def close(self) -> None: ...anddef cleanup(resource: SupportsClose) -> None:that callsclose; pass one class that definescloseand one that does not, and explain which the checker accepts. - Make both protocols
@runtime_checkableand compareisinstanceresults for a class whose method signatures differ from the protocol; state what the runtime check actually tested. - Convert
SupportsWriteinto a small ABC with an abstractwriteand list what changes: subclasses must inherit, instantiation is blocked untilwriteexists, and shared helper methods become possible.
Practice: Hard
- Write one function that accepts a
SupportsWriteprotocol and one that accepts an ABC with the same method; create a class that only implements the method and pass it to both, then explain what it satisfies without edits. - Failure lab: trigger the
TypeErrorfromisinstanceon a plain protocol, a passingisinstanceon aruntime_checkableprotocol whose call still raisesTypeError, and a class that runs fine yet fails the checker; explain each mechanism. - Decide protocol or ABC for two scenarios, a plugin interface for classes you cannot modify and an internal hierarchy that shares a cache, and justify each choice from what the interface must guarantee at runtime.
Lesson checklist
- I can define a protocol and explain why an unrelated class satisfies it.
- I can tell structural subtyping apart from inheritance with a concrete pair of classes.
- I can state what
@runtime_checkabledoes and does not verify in anisinstancecheck. - I can choose protocol or ABC from what the interface must guarantee.
Remember
A protocol describes the members a value must have, and the checker compares shapes rather than class lineages, so duck typing gains a static, checkable form. `@runtime_checkable` adds a shallow `isinstance` check that tests member presence only, while an ABC stays the tool for shared implementation and instantiation-time enforcement. Draw the line where it matters: protocols describe what callers must provide, and ABCs enforce what subclasses must implement.
Interview angles
What is the main purpose of **Protocol**?+
Protocol defines a structural static interface. A class can satisfy the protocol without explicitly inheriting from it if its available members match the required shape.
What should you pay attention to when using **Structural subtyping**?+
Structural subtyping accepts a class for a type when its members match the required shape, with no inheritance involved, so unrelated classes can satisfy the same protocol. The checker compares attributes and method signatures at the use site.
How does **Static duck typing** fit into this lesson?+
Static duck typing applies duck typing at check time: if an object provides the operations a protocol requires, the checker accepts it, and a wrong method signature is reported before the program runs. At runtime nothing is inspected.
What does `isinstance(obj, SupportsWrite)` actually verify for a `@runtime_checkable` protocol?+
It verifies only that the required members exist on the object, not their signatures or behavior. Methods are present or absent; argument types and return types are never checked at runtime.