Static type checking analyzes code against type contracts without relying on running every possible execution path.
Connect annotations, checker diagnostics and runtime validation, and distinguish their different responsibilities.
A function expects an integer, while an API sends the string "3". A type annotation documents the internal contract; it does not decide whether incoming data should be rejected or converted. Separate static checking, runtime validation and business rules, then test each boundary with a different kind of bad input.

Hint a function's shape
A hint documents what a function expects, for a human reading it and for a tool checking it — never for Python itself:
Both show the same three entries: name, times, and return. typing
adds vocabulary for shapes a bare class can't express: list[int] (a list of
ints), dict[str, int] (string keys, int values), int | None (an int,
or nothing — the modern spelling of Optional[int]), and TypedDict for a
dict with a fixed, named set of keys, each with its own type. None of these
change what the function does — only what a reader, or a checker, can tell
about it:
def greet(name: str, times: int) -> str:
return (name + " ") * times
print(greet("hi", "3"))Preparing this topic’s interactive investigation…
Catch a bug before it ships
mypy and pyright read your source without running it, analyze the configured code and check known argument types against the function's hints. Point either one at the file above and it reports the mismatch before anything executes:
$ mypy app.py
app.py:5: error: Argument 2 to "greet" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)
$ pyright app.py
app.py:5:18 - error: Argument of type "Literal['3']" is not assignable to parameter "times"
of type "int" (reportArgumentType)
1 error, 0 warnings, 0 informationsSame bug, same line, caught at two different moments: mypy/pyright catch it before the program runs at all; without them, Python only finds out when that exact line executes — a code path a quick test run might never reach.
Validate data at the door
Hints describe shape to a checker. Pydantic goes further and actually enforces a shape at runtime, which matters most at the edges of a program — data arriving from a request body, a config file, a database row, none of which ever ran through mypy:
from pydantic import BaseModel
class Order(BaseModel):
item: str
quantity: int
Order(item="Pens", quantity=3) # fine — builds the object
Order(item="Pens", quantity="three") # raises ValidationError, right here, at runtime"three" can't become an int, so Pydantic raises immediately — the one
place in this lesson a type mismatch actually stops a program on its own.
That's the trade mypy/pyright don't make: validation occurs where you explicitly construct or validate a model,
with runtime work and a chosen coercion policy. It complements static
checking instead of replacing it.
Three more names worth knowing by what they're for, not what they check:
pyenv installs and switches between Python versions themselves (3.11 vs
3.12) — nothing to do with typing. Pipenv and virtualenv manage
per-project environments, the same job venv does (section-15 covers
that in full) — Pipenv adds a lockfile on top. pyre is Meta's own static
checker, a third alternative to mypy and pyright, same idea, different tool.
Validate values at the boundary, then rely on the established contract
An API supplies {"quantity": "3"}. A static annotation cannot inspect that future payload. Runtime validation must decide whether to reject the string or convert it to an integer; after that decision, internal functions can work with the established type.
Pydantic's default mode may coerce compatible values, while strict mode rejects many such conversions. Neither behavior is automatically right for every field. A form field may reasonably accept "3"; a protocol requiring a JSON integer may need to reject it. Separately, an integer quantity of -3 has the correct type but may violate the business rule.
True is an instance of int in Python, so the deliberate type(raw) is int check expresses a stricter boundary than isinstance. The exercise's simpler checker retains its isinstance contract; do not infer that it implements full typing semantics.
int | None permits a value to be None; it does not by itself make a function argument omittable or a dictionary key optional. Defaults and TypedDict key-requiredness are separate. The optional-record exercise adopts an extra missing-field policy, which should be named as application policy.
For transfer, design a request with a required integer id, an optional note and a nonnegative duration. Distinguish a missing key, a present None, a wrong type and a valid type with an invalid value. Write one case for each before choosing annotations or a validation library. Annotation introspection itself can evaluate names or expressions; use it on trusted application code.
References: typing semantics and Pydantic strict mode.
Quick practice
def area(width: float, height: float) -> float:
return width * height
print(area(3, 4), type(area(3, 4)))def ship(weight: "int"):
pass
print(ship.__annotations__)mypy reports an error on a line that Python runs without crashing every single time in production. What does that mean?
from typing import Optional
def find_user(id: int) -> Optional[str]:
return None
result = find_user(5)
print(result is None, result == "")🎯 Your turn
Write type_check(args). It checks a fixed function, safe_divide(a: int, b: int) -> float, against the two values in args (positionally: args[0] is
a, args[1] is b). Use safe_divide.__annotations__ and
safe_divide.__code__.co_varnames to find each parameter's expected type,
and isinstance to check the matching value. Return True only if every
value matches its hint.
type_check([10, 2])→Truetype_check([10, "2"])→False
Hint: names = safe_divide.__code__.co_varnames[:safe_divide.__code__.co_argcount]
gives you ("a", "b") in order; zip(names, args) pairs each one with its
value.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds a small runtime validator out of the same annotation-reading idea.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write is_optional(hint). hint is a type written as a string, like "int | None" or "Optional[int]" or "str". Return True if the hint allows None.
Write base_type(hint). Given a hint string, return just the underlying type name: "list[int]" -> "list", "int | None" -> "int", "Optional[str]" -> "str", "int" -> "int".
Write matches_type(value, type_name). type_name is one of "int", "str", "float", "bool", "list", "dict". Return whether value is actually that type. An unrecognised type_name should return False.
Write validate_record(record, schema). schema is a dict of {field: type_name}. Return True only if every field in schema is present in record AND matches its type (reuse the same type-name lookup as matches_type).
Write validate_optional_record(record, schema). schema values are hint strings like "str" or "int | None". A field whose hint is optional may be missing from record or None. A field whose hint is NOT optional must be present and non-None, and must match its base type.