Lesson · Type Hints & Static Typing
Type Hint Fundamentals
74 min readType Hint Fundamentals
Type hints describe expected shapes for static analysis and documentation; they do not normally enforce values at runtime. Python 3.14 also changes how annotations are evaluated, making forward references and introspection more flexible.
Learning goals
- Annotate parameters and return values, and say what those annotations attach to at definition time.
- Read annotations back with
__annotations__,get_type_hints(), andannotationlib, and explain what each form returns. - Replace
typing.Liststyle spellings with built-in generics such aslist[str]anddict[str, int]. - Model a possibly missing value with
T | Noneand check it before use. - Explain how Python 3.14 defers annotation evaluation and why a forward reference works without quotes.
Mental model
One annotation serves two consumers: a checker reads the shapes while you edit, and runtime tools read the same metadata through __annotations__ or the annotation APIs. In Python 3.14 the stored annotation is deferred rather than evaluated at definition time, so the runtime side chooses the form it materializes.
Mental model
read it top to bottom
source annotations ├── static checker at analysis time: parameter and return shapes └── runtime introspection: __annotations__, get_type_hints(), annotationlib
Version note
Python 3.14 changes annotation evaluation semantics and adds annotationlib. Runtime annotation tools should account for deferred evaluation.
Core idea
An annotation is metadata attached to a parameter, return value, or variable, and its job is to state an intended shape rather than enforce one. Static checkers read those shapes ahead of runtime, while runtime tools read them through __annotations__, get_type_hints(), or annotationlib. The rule to internalize: annotations describe, and the call itself still does whatever the objects allow.
Function annotations
Function annotations attach metadata to parameters and return values. Type checkers interpret them statically, while runtime code can introspect them when needed.
Variable annotations
A variable annotation attaches a type to a name without creating a binding: count: int records intent but assigns nothing. At module and class level the annotation is stored in __annotations__, which is how dataclasses and similar tools discover field types; touching the name before assignment raises NameError.
Built-in generic syntax
Built-in collections accept type arguments directly: list[str], dict[str, int], tuple[int, ...]. This spelling replaced the older typing.List style, and at runtime the subscription builds a types.GenericAlias rather than a new class.
None
None is Python's single object for absence: its type is NoneType, and there is exactly one instance. In annotations it appears inside a union such as str | None to mark a value that may be missing, and a function that reaches its end without return hands back None implicitly.
Union types
A union states that a value can have one of several types. A type such as T | None explicitly models absence instead of hiding it in an undocumented convention.
Optional values
A union states that a value can have one of several types. A type such as T | None explicitly models absence instead of hiding it in an undocumented convention.
Static typing vs runtime behavior
A type checker can reject suspicious code before execution, but Python normally does not enforce annotations when a function is called. Runtime validation is a separate concern.
Deferred evaluation of annotations in Python 3.14
Python 3.14 defers annotation evaluation by default, reducing definition-time cost and making forward references easier. Code that introspects annotations should use supported annotation APIs rather than assuming older eager behavior.
annotationlib overview for runtime annotation introspection
Python 3.14 adds annotationlib to inspect annotations in different formats. This lets tools request evaluated values, forward-reference-aware forms, or strings depending on their needs.
Forward references without string quoting in modern Python
Python 3.14 does not evaluate annotations when the function or class is defined, so a forward reference such as def transform(value: UndefinedType) -> ResultType: is legal before those names exist. The annotation is resolved later, when a tool asks for the evaluated form through annotationlib or typing.get_type_hints().
Python 3.14 example: deferred annotations
The function can be defined even though those names are not runtime values at definition time. Introspection code chooses how annotations should be materialized.
from annotationlib import Format, get_annotations def transform(value: UndefinedType) -> ResultType: ... print(get_annotations(transform, format=Format.STRING))
Common mistakes
- Assuming annotations enforce values: the interpreter never checks them at call time, so
repeat("hi", "3")fails later, inside[text] * count, with aTypeError. - Reading
__annotations__and expecting resolved types: depending on how the module was compiled the dict can hold strings or deferred forms, so useget_type_hints()orannotationlibwhen you need real objects. - Treating a variable annotation as an assignment:
total: intrecords metadata only, and evaluatingtotalbefore any assignment raisesNameError. - Annotating every local in a short function: a checker already infers local types from their assignments, so extra annotations add noise at the exact spots where the types are obvious.
Practice: Easy
- Run the worked example and match each printed key in
repeat.__annotations__to a part of the signature, including the'return'entry. - Change
repeattodef repeat(items: list[int], count: int) -> list[int]:with an updated body, and confirm the printed annotations follow the new signature. - Write three unassigned module-level annotations (
name: str,scores: list[float],pairs: dict[str, int]), print__annotations__, and access one name to see theNameError.
Practice: Medium
- Take a small function annotated with
typing.List[str]andtyping.Dict[str, int]and rewrite it withlist[str]anddict[str, int]; confirm it still runs and the annotations still print. - Print
annotationlib.get_annotations(repeat, format=Format.STRING)next to the default format; decide which one a logging tool should show and which one a runtime dispatcher needs. - Write
find(records: list[dict[str, str]], key: str) -> dict[str, str] | None:that returns the first record matchingkey; call it with a missing key, read the real return value at runtime, and show the caller guard that handles it.
Practice: Hard
- Write
check_shape(func, args)that compares each argument with the shapes fromget_type_hints(func)and prints a report; run it onrepeat("hi", "3")and decide whether such a runtime checker belongs in production code. - Failure lab: trigger the
NameErrorfrom reading an unassigned annotated variable, theTypeErrorfromisinstance([], list[str]), and theNameErrorfrom asking forFormat.VALUEon the deferred example; explain the mechanism behind each result. - Request all four
annotationlibformats for the annotations oftransformand write one sentence per format describing which tool would ask for it: evaluated objects, fake-globals evaluation, forward-reference proxies, or raw strings.
Lesson checklist
- I can write parameter, return, and variable annotations and read them back with
__annotations__andget_type_hints(). - I can explain what
list[str]is at runtime and whyisinstancerejects it. - I can model a possibly missing result with
T | Noneand guard the caller. - I can explain why a forward reference works in 3.14 without quotes and when to reach for
annotationlib.
Remember
Type hints attach intended shapes to parameters, returns, and variables, and their value lives in what reads them: static checkers before runtime, introspection tools during it. Python 3.14 defers evaluation, so `def transform(value: UndefinedType) -> ResultType:` is legal and `annotationlib` lets each tool request the form it needs. Keep the split in mind: the signature is a contract the checker trusts, never a gate the interpreter enforces.
Interview angles
What is the main purpose of **Function annotations**?+
Function annotations attach metadata to parameters and return values. Type checkers interpret them statically, while runtime code can introspect them when needed.
What should you pay attention to when using **Variable annotations**?+
A variable annotation such as count: int records the intended shape without binding a value. At module and class level it lands in __annotations__, and evaluating the name before it is assigned raises NameError.
How does **Built-in generic syntax** fit into this lesson?+
Built-in collections accept type arguments directly, so list[str] and dict[str, int] replace the older typing.List and typing.Dict spellings. At runtime list[str] is a types.GenericAlias, and it cannot be used inside isinstance.
Why does `repeat("hi", "3")` run at all when `count` is annotated `int`?+
Annotations are metadata, not enforcement: Python never checks them at call time. The call proceeds into the body and fails at [text] * count, where multiplying a list by a string raises TypeError.