Lesson · Type Hints & Static Typing
Advanced Typing Concepts
65 min readAdvanced Typing Concepts
Advanced typing features such as overloads, `TypedDict`, `Self`, `ParamSpec`, type guards, and `Annotated` solve specific modeling problems. They are valuable when a simpler annotation cannot accurately express the contract.
Learning goals
- Declare several call forms for one function with
@overloadand explain which signature the checker applies at a call site. - Describe dictionary-shaped data with
TypedDictand say what the value remains at runtime. - Return the calling instance type from a fluent method with
Self. - Use
ParamSpecto keep a decorator's typed signature faithful to the wrapped function. - Attach runtime metadata with
Annotatedand write a type guard that narrows for the checker.
Mental model
Each feature exists for one modeling problem that a plain annotation cannot express, so identify the problem first and the tool follows. None of them changes runtime behavior beyond storing metadata.
Mental model
read it top to bottom
problem tool one function, several call shapes @overload dictionary with fixed keys and types TypedDict method returns "the same kind of object" Self decorator must preserve the wrapped sig ParamSpec custom check narrows its argument TypeGuard / TypeIs type plus extra runtime information Annotated
Core idea
These features exist because a single plain annotation cannot express every contract: several call shapes need @overload, fixed dictionary keys need TypedDict, fluent methods need Self, decorators need ParamSpec, custom checks need a type guard, and runtime consumers need Annotated. Each adds a narrow, precise statement to the checker's model without adding runtime machinery. The discipline matches the simpler lessons: reach for the smallest tool that expresses the contract, since every step up the ladder costs readability.
Overloads
@overload declarations describe several typed signatures for one implementation: each covers one accepted call form, and a final undecorated def holds the real body. The checker picks the matching overload at each call site, while at runtime only that final implementation executes and the declarations are discarded.
TypedDict
TypedDict describes the expected keys and value types of dictionary-shaped data to a static type checker. At runtime the value remains an ordinary dictionary.
Self types
Self in a return annotation means the type of the instance the method was called on, so a base-class method returns whatever subclass it actually ran for. Without it, a fluent method annotated with the class name narrows every chain to the base class once a subclass joins in.
ParamSpec
ParamSpec captures a callable parameter list so wrappers can preserve or transform call signatures in type annotations. It is particularly useful for well-typed decorators.
Type guards
A type guard is a function annotated with TypeGuard (or TypeIs for two-way narrowing) whose boolean result tells the checker that its argument has the narrower type when the result is true. The body performs the real runtime check, and the annotation carries the conclusion back into the caller's control flow.
Type narrowing
Type narrowing uses control flow to refine a broad static type after checks such as isinstance, is None, or a type guard. Good narrowing mirrors real runtime guarantees.
Annotated types
Annotated[int, "positive"] attaches metadata to a type without changing the type itself: a checker still sees int, while frameworks read the extra arguments at runtime. It is the standard hook for validation libraries and dependency injection that need supplemental information alongside a type.
Walkthrough
class UserRecord(TypedDict)fixes the keysnameandagewith their value types; the literal{"name": "Ada", "age": 36}is checked against that shape but stays an ordinarydictat runtime.def add(self, part: str) -> Self:returns the same instance, soBuilder().add("a").add("b")chains without the checker losing track of the type; at runtime the method returnsselflike any other.self.parts: list[str]starts as an empty list in__init__and grows throughappend, so.partsat the end of the chain prints the accumulated['a', 'b'].- Predict before running: the printed value, what the checker knows about
add's return when the receiver is a subclass ofBuilder, and what runtime error appears ifaddforgetsreturn self.
Experiments to try
- Add an extra key to the
userliteral and assign it to theUserRecordvariable; note what the checker reports and confirm the script runs anyway. - Add a required
email: strkey toUserRecordand remove it from the literal; record the checker error, then run the script and see that nothing raises. - Replace
Selfwith"Builder"inadd's return annotation and explain what the checker can no longer promise for a subclass that adds another chained step. - Annotate a helper as
def check(value: Annotated[int, "positive"]) -> None:and print its__annotations__entry; confirm the metadata is stored while the checker still sees a plainint.
Common mistakes
- Expecting
TypedDictto enforce keys at runtime: the value is a plaindict, so missing or extra keys run fine and only the checker objects to the literal. - Calling a function that has only
@overloaddeclarations: the decorator installs a stub that raisesNotImplementedError, and the real behavior must live in a final undecorateddef. - Annotating a fluent method with the class name instead of
Self: a subclass call collapses the chain to the base class in the checker's view and hides subclass-only methods. - Writing a type guard that does not actually check: the annotation is trusted, not verified, so a lying
TypeGuard[str]convinces the checker that later string operations are safe.
Practice: Easy
- Run the worked example, then delete
agefrom theuserliteral; confirm the script still runs and describe the checker's complaint. - Print
type(user)and confirm thatUserRecordproduced an ordinarydictat runtime. - Add a third
addcall to the chain and print the final.parts; then removereturn selfand read the runtimeAttributeErrorthat follows.
Practice: Medium
- Sketch three
@overloadsignatures for aconvert(value)function coveringint,str, andbytesinputs with one implementation; state which signature the checker applies to each call. - Replace
Selfwith"Builder"inaddand explain what a checker can no longer promise for a subclass that adds another chained step. - Write
def is_number(value: object) -> TypeGuard[int]:returningisinstance(value, int); call it on a variable typedobjectand show the checker treats the variable asintinside the true branch.
Practice: Hard
- Write a
loggeddecorator withP = ParamSpec("P")anddef logged(fn: Callable[P, int]) -> Callable[P, int]:that wraps*args: P.args, **kwargs: P.kwargs; verify the checker keeps the wrapped function's parameter list after decoration. - Failure lab: call a function that has only
@overloadstubs, pass a dict missing a requiredTypedDictkey, and write a checking function whoseTypeGuardannotation lies; explain each mechanism and which failures only a checker sees. - Build two
TypedDicts, a request and a response, for one call and annotate the function end to end; list each mismatch the checker catches and each place the runtime would only fail later.
Lesson checklist
- I can declare
@overloadsignatures and name the one implementation that runs. - I can describe dictionary-shaped data with
TypedDictand say what remains at runtime, a plaindict. - I can use
Selfin a fluent method and explain what a checker keeps that a class-name annotation would lose. - I can attach metadata with
Annotatedand narrow a type with aTypeGuardfunction.
Remember
Overloads, `TypedDict`, `Self`, `ParamSpec`, type guards, and `Annotated` each solve one modeling problem a plain annotation cannot: several call shapes, fixed dictionary keys, identity of the receiver, faithful decorator signatures, narrowing from a custom check, and runtime metadata. They extend the checker's model, not the interpreter's behavior, so the same discipline applies: use the smallest tool that states the contract, knowing every one of these promises is checked statically and verified nowhere at runtime.
Interview angles
What is the main purpose of **Overloads**?+
@overload declarations describe several typed signatures for one implementation, one per accepted call form, with the real body in a final undecorated def. The checker picks the matching overload at each call site, while only the final implementation runs at runtime.
What should you pay attention to when using **TypedDict**?+
TypedDict describes the expected keys and value types of dictionary-shaped data to a static type checker. At runtime the value remains an ordinary dictionary.
How does **Self types** fit into this lesson?+
Self in a return annotation stands for the type of the instance the method was called on, so a base-class method returns the subclass type it actually ran for. That keeps fluent chains typed even when subclasses extend the class.
Why does a `dict` that is missing a `TypedDict` key still run?+
TypedDict is a checker-level description: at runtime the value is an ordinary dict, so missing or extra keys do not raise. Only the checker flags a literal that does not match the declared shape.