Recipes: Type hints¶
Task-focused how-tos. If you know what you want to do but aren't sure how to type it, this is the section to skim.
Recipes in this section¶
- Type a function signature — parameters, defaults, variadic args (
*args,**kwargs), return types, and how to document what a function actually takes. - Type a data structure — when to use
TypedDict, when to use a dataclass, whenNamedTuplefits, and when a plaindict[str, int]is enough. - Work with
Optionalvalues — theX | Nonepattern, narrowing withif x is not None, and whyOptional[X]doesn't mean "this argument has a default". - Avoid common typing mistakes — a short catalogue of the traps:
listvsList, mutable defaults, forward references, variance gotchas.