Learn with diagrams, code, systems and practical examples.
Type Hints
Document expected data shapes and improve tooling without changing Python into a statically typed language.
Type hints make function contracts easier to understand and help editors and static analysis catch mismatches earlier.
Start with the idea
Annotations describe expected types for parameters, return values, and variables. Python still runs dynamically, but tools can use the annotations for checking and navigation.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
def total(values: list[float]) -> float:
return sum(values)
print(total([1.5, 2.5])) Annotations describe expected types for parameters, return values, and variables. Python still runs dynamically, but tools can use the annotations for checking and navigation.
- Type hints document intent.
- Static tools can check them.
- Runtime validation is a separate concern.
4.0The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Assuming type hints automatically validate runtime input.
Use type hints for contracts and tooling; add runtime validation separately when external input must be checked.
Quick recap
- Type hints document intent.
- Static tools can check them.
- Runtime validation is a separate concern.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Add type hints to two earlier functions.
- Create a function that returns dict[str, int].