Design Data Helpers with Python TypedDict and Literal
Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.
Python code
24 linesfrom typing import TypedDict, Literal, Optional, Union, List
class User(TypedDict):
name: str
age: int
role: Literal["admin", "user", "guest"]
def describeUser(data: User) -> str:
return f"{data['name']} ({data['age']}) — {data['role']}"
def parse_value(item: Union[int, str, None]) -> str:
if item is None:
return "None provided"
if isinstance(item, int):
return f"Number: {item}"
return f"Text: {item}"
if __name__ == "__main__":
user: User = {"name": "Alice", "age": 30, "role": "admin"}
print(describeUser(user))
items: List[Union[int, str, None]] = [42, "hello", None, "world"]
for value in items:
print(parse_value(value))
Output
Alice (30) — admin
Number: 42
Text: hello
None provided
Text: world
How it works
TypedDict lets you define the expected dictionary structure with type annotations, and Literal restricts a field to specific values. Union allows a value to be one of several types, which parse_value handles with isinstance checks. Type hints improve code clarity and enable static type checkers to catch errors early, though they do not affect runtime behavior. The if __name__ == "__main__" guard ensures the demo only runs when the script is executed directly, not when imported.
Common mistakes
- Forgetting that TypedDict is only a hint — it does not enforce types at runtime.
- Using `isinstance` with a `Union` but missing a case, leading to unexpected fallthrough.
- Assuming `Literal` restricts input values at runtime; it is only for static checking.
Variations
- Use `from __future__ import annotations` to write the `User` annotation as a string in some contexts.
- Replace `Union[int, str, None]` with `int | str | None` in Python 3.10+ for a more concise syntax.
Real-world use cases
- Defining API request payload types in a service to ensure consistent data shapes.
- Typing configuration dictionaries read from files to catch missing keys with a static checker.
- Writing helper functions that handle different data types in data preprocessing pipelines.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
- Format Data with Type Hints in Python easy
Keep learning
Related tutorials and quizzes for this topic.