Protocols (PEP 544)
Structural subtyping
Interview Relevant: Modern Python typing
Protocols
Structural subtyping for duck typing.
Code Examples
Protocols for structural typing.
python
1from typing import Protocol, runtime_checkable
2
3class Sized(Protocol):
4 def __len__(self) -> int: ...
5
6class Iterable(Protocol):
7 def __iter__(self): ...
8
9# Custom protocol
10@runtime_checkable
11class Closeable(Protocol):
12 def close(self) -> None: ...
13
14class File:
15 def close(self):
16 print("Closing file")
17
18class Connection:
19 def close(self):
20 print("Closing connection")
21
22def cleanup(resource: Closeable):
23 resource.close()
24
25# Works with any class that has close()
26cleanup(File())
27cleanup(Connection())
28
29# Runtime check
30isinstance(File(), Closeable) # True