Advanced · 14 min
Type hints and protocols
Describe interfaces that different objects can satisfy.
Annotate intent
Type hints document expected inputs and outputs. Python still executes the function normally at runtime.
def total(values: list[int]) -> int:
return sum(values)
print(total([2, 4, 6]))Output
12
Describe shared behavior
A Protocol names the methods an object should provide. Unrelated classes can satisfy it without inheritance.
from typing import Protocol
class Named(Protocol):
def name(self) -> str: ...
class User:
def name(self) -> str:
return "Ada"
def label(item: Named) -> str:
return item.name().upper()
print(label(User()))Output
ADA
Type hints and protocols
- Read both type hints and protocols examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Use a common interface
Add a title method to Article so it satisfies Titled. Keep the display call and output Python Tips.
Article needs a title method that returns self.text.