Sub topic 2
Literal aliases, unions and tagged dictionaries
This chapter assumes basic Python dictionaries, functions, classes, and type hints. It also assumes that you have used a static type checker such as mypy or pyright.
Literal aliases and unions
Literal restricts a value to specific constants. An alias gives that set a reusable name:
from typing import Literal
Mode = Literal["r", "w", "a"]
Result = Mode | None
def choose_mode(mode: Mode) -> None:
print(f"mode: {mode}")
choose_mode("r") # accepted
choose_mode("x") # reported by a type checkerA union, written with |, combines allowed types or literal sets. Result means either one of the three mode strings or None.
Literal values can include strings, integers, booleans, None, and supported enum members. Use constant values directly. A computed expression such as Literal[1 + 1] is not a portable way to declare a literal type.
Runtime behavior: plain dictionaries and no validation
Literal and TypedDict guide static analysis. Python does not automatically check them when the program runs. A TypedDict value is still an ordinary dict, and a Literal annotation does not reject an unexpected value.
from typing import Literal, TypedDict
Kind = Literal["user", "service"]
class Identity(TypedDict):
kind: Kind
name: str
item: Identity = {"kind": "other", "name": "example"}
print(item["kind"])The assignment should be reported by a type checker, but this program runs normally.
Narrowing and exhaustiveness
A checker can narrow a union after comparing a Literal value. assert_never makes an unhandled case visible to the checker:
from typing import Literal, assert_never
Status = Literal["queued", "done"]
def message(status: Status) -> str:
if status == "queued":
return "Waiting"
if status == "done":
return "Finished"
assert_never(status)If Status later gains "failed", the final line alerts you that message needs another branch.
Tagged unions with TypedDict
A tagged union combines several dictionary shapes. Each shape has a shared key whose literal value identifies that shape.
from typing import Literal, TypedDict, assert_never
class UserEvent(TypedDict):
kind: Literal["user"]
user_id: int
class ErrorEvent(TypedDict):
kind: Literal["error"]
message: str
Event = UserEvent | ErrorEvent
def describe(event: Event) -> str:
if event["kind"] == "user":
return f"user {event['user_id']}"
if event["kind"] == "error":
return f"error: {event['message']}"
assert_never(event)The kind check narrows event to the matching TypedDict shape.
Exercise
What does a type checker learn from event["kind"] == "error"?
Show answer
It narrows the event to ErrorEvent, so accessing event["message"] is valid.