Precise hints: generics, Protocol, TypedDict and Literal
🌍 In real life. Labels can be more precise than "box":
- a lunch box that says "what goes in comes out": put rice in, get rice back; put fruit in, get fruit back
- a socket that says "anything with this plug": it doesn't care which company made the kettle
- an admission form with exactly these blanks: name (text), age (number)
- a bus ticket that is "AC" or "non-AC", and nothing else
Python's type hints (Lessons 29.1–29.3) have a tool for each of these.
The idea in one sentence: a type variable lets a hint say "the same type comes out as went in", a Protocol says "anything with these methods", a TypedDict says "a dict with exactly these keys", and Literal says "only these exact values".
Its words:
- type variable: a stand-in name,
T, for "some type, the same each time it appears";def first[T](items: list[T]) -> T(Python 3.12 and later) - generic: a function or class written with a type variable, so it works for many types and keeps track of which
Protocol: a class that lists methods; any class with those methods fits, without inheriting from it (duck typing, Lesson 22.3, written as a hint)TypedDict: names each key of a dict and the type of its valueLiteral["S", "M", "L"]: only these values are allowed
Step by step, for first([30, 10, 20]):
- The list is a
list[int], so for this callTstands forint. - The hint
-> Tthen says the answer is anint: a checker knowstop + 1is fine. - For
first(["tea", "coffee"]),Tisstr, and the answer is astr. - When the program runs, nothing extra happens: hints are labels for people and checkers.
Protocol: a hint for duck typing. In Lesson 22.3 a Duck and a Robot both had speak(), and one loop worked for both. A Protocol writes that rule down: "a Speaker is anything with a speak() that returns a str". Neither class has to inherit from Speaker; a checker looks at the methods they have.
from typing import Protocol
class Speaker(Protocol):
def speak(self) -> str: ...
class Duck:
def speak(self) -> str:
return "Quack"
class Robot:
def speak(self) -> str:
return "Beep"
def greet_all(things: list[Speaker]) -> None:
for thing in things:
print(thing.speak())
greet_all([Duck(), Robot()])from typing import Literal, TypedDict
class Contact(TypedDict):
name: str
phone: str
Seat = Literal["AC", "non-AC"]
def ticket(who: Contact, seat: Seat) -> str:
return f"{who['name']}: {seat}"
c: Contact = {"name": "Mina", "phone": "017-111"}
print(ticket(c, "AC"))
print(type(c).__name__)The older spelling. Before Python 3.12, type variables were made by hand: T = TypeVar("T"), then def first(items: list[T]) -> T:. You will see this in a lot of code; it means the same.
What it costs. Nothing at run time. In return, a checker can catch a wrong key in a dict, a size that doesn't exist, or an object missing a method, before anyone runs the program.
Mistakes and edge cases.
- Expecting Python to enforce them.
ticket(c, "first class")runs without complaint; only a checker flags it. Guard real input yourself (Lesson 29.4). - isinstance with a TypedDict.
isinstance(c, Contact)givesTypeError: TypedDict does not support instance and class checks. At run time it is just a dict: check its keys instead. - isinstance with a Protocol.
isinstance(Duck(), Speaker)givesTypeError: Instance and class checks can only be used with @runtime_checkable protocols. Add@runtime_checkablefromtypingif you really need it. - A type variable used once.
def show[T](x: T) -> Noneadds nothing overx: object. A type variable earns its place when it links two things, like what goes in and what comes out.
Quiz
def first[T](items: list[T]) -> T. What does a checker know about first(["a", "b"])?
- It is a str
- It is a list
- Nothing: T could be any type
What does this print?
from typing import TypedDict class Point(TypedDict): x: int y: int p: Point = {"x": 1, "y": 2} print(type(p).__name__, p["x"] + p["y"])Speaker is a Protocol with speak(). Robot has a speak() but doesn't inherit from Speaker. Does a checker accept a Robot where a Speaker is wanted?
- Yes: a Protocol only asks for the methods
- No: Robot must inherit from Speaker
- Only if Robot also has __init__
A checker flags this before it runs, and Python stops with KeyError: 'XL'. Which line breaks the hint?
from typing import Literal Size = Literal["S", "M", "L"] def price(size: Size) -> int: return {"S": 20, "M": 30, "L": 40}[size] print(price("XL"))What does this print?
from typing import Literal def move(direction: Literal["up", "down"]) -> str: return "going " + direction print(move("sideways"))
Coding tasks
Write a generic function with the new syntax,
def last[T](items: list[T]) -> T | None:, that returns the last item, orNonefor an empty list.Make
Book, a TypedDict withtitle: strandpages: int. Then writereading_time(book: Book, speed: Literal["slow", "fast"]) -> int: 2 minutes a page when slow, 1 when fast.