Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Advanced Python & Software Engineering — Alpha School

Lesson 13: Type Hints and Static Checking

Python is dynamically typed: a variable can hold a number now and a string later, and Python only finds out about a type mistake when the code actually runs. That flexibility is part of what makes Python pleasant to write, but in a large program it also means a whole class of bugs that only appear at runtime — often in the one code path nobody tested. Type hints are the compromise: you annotate what types a function expects and returns, and a separate tool checks those annotations without running your code. The hints are ignored at runtime, so they cost nothing when the program runs, but they catch mistakes early and make code far easier to read.

The syntax is simple. You write def greet(name: str) -> str: to say the function takes a string and returns a string. For collections you use the built-in generic forms: list[int], dict[str, int], tuple[str, int], and int | None for a value that may be missing. The example below is a small grade-book function, fully annotated, including an Optional-style union for a score that might not exist yet.

def average(scores: list[float]) -> float:
    if not scores:
        raise ValueError("cannot average an empty list")
    return sum(scores) / len(scores)


def best_student(grades: dict[str, list[float]]) -> str | None:
    if not grades:
        return None
    return max(grades, key=lambda name: average(grades[name]))


print(average([8.5, 9.0, 7.5]))  # 8.333...
print(best_student({"ana": [9.0, 8.0], "ben": [7.0, 7.5]}))  # ana

Checking with mypy, and the limits of hints

Hints on their own do nothing — Python ignores them. The checking is done by a tool such as mypy, which reads your code and your hints and reports mismatches, such as passing a string where a list of numbers was promised. Running a checker is a habit worth building into any project: it finds the same class of mistake that a compiler would catch in a statically typed language, while leaving Python's runtime flexibility intact. Most editors can run a checker as you type, underlining problems before you ever run the program.

There are limits, and honesty about them matters. Hints do not make Python fast, they do not change what the code does, and they cannot describe every clever dynamic trick — for those cases you can use Any, which means the checker should not look too closely. The goal is not to annotate every variable in a short script; it is to annotate the boundaries of your code — function signatures, public APIs, data structures — where a wrong type causes the most confusion. A function whose signature says exactly what it takes and returns is documentation that can never go out of date, because the checker verifies it.

Going further

Type hints are deliberately gradual: you can add them to one function, one file, or one module at a time, and leave the rest of your code unannotated. That matters for real projects, where annotating everything at once is unrealistic. A good place to start is the boundary of your code — the public functions other people call — because that is where a wrong type causes the most confusion. Internal helper functions can stay unannotated until they need it. The checker only verifies what you annotate, so partial hints still catch real mistakes.

Hints can also describe your own classes, not just built-in types. A function that takes a BankAccount says so in its signature, and the checker will flag a call that passes a string instead. For variables, you can write total: int = 0 to annotate a name at the point you create it. And for functions that return nothing, the return hint is None — written -> None — which is a small but useful piece of documentation: it tells the reader the function is called for its effect, not its result.

To see the value of a checker, try a small experiment: take a function you wrote earlier in this course, add type hints to its signature, and run mypy on it — you can install it with pip install mypy inside a virtual environment. Then deliberately call the function with the wrong type and run mypy again. The checker will point at the exact line and name the mismatch, before the program has run at all. That early warning is the whole product: a mistake caught by a tool in seconds, instead of by a user in production, or by you at midnight, three weeks later, when you have forgotten what the function was supposed to do.

Key Terms

Dynamically typed
Types are checked at runtime; a variable can hold values of different types over time.
Type hint (annotation)
A note in the code stating the expected type of a variable, parameter or return value.
Static checking
Verifying types without running the code, using a tool such as mypy.
mypy
The most widely used static type checker for Python; it reads hints and reports mismatches.
list[int]
A hint meaning a list whose items are integers; dict[str, int] and tuple[str, int] work the same way.
Union type
A hint meaning one of several types, written with |, such as str | None.
Any
A hint meaning any type is allowed; the checker will not verify values annotated this way.

Discussion Questions

  1. Type hints are ignored at runtime. So what do they actually buy you? Who benefits most — you, your teammates, or your tools?
  2. When is it worth annotating a function, and when is it overkill? Think about a five-line script versus a shared library.
  3. If a checker reports that you passed a string where an int was expected, is that a bug in your code or a bug in your hints? How do you decide?

Practice Questions

  1. What does def average(scores: list[float]) -> float: promise?
  2. What type hint describes a dictionary mapping names (strings) to ages (integers)?
  3. What does str | None mean?
  4. What happens at runtime if you pass a string to a parameter hinted as int?
  5. Annotate a function double that takes an int and returns an int.
Show answers
  1. It takes a list of floats and returns a float. The hints describe the contract; mypy checks callers keep it, but Python itself ignores them at runtime.
  2. dict[str, int]. The first type is the key type, the second is the value type.
  3. A value that is either a string or None. It is a union type, written with the | operator.
  4. Nothing special — Python ignores the hint and runs the code. The mistake is only caught if a checker like mypy is run, or when the code fails later.
  5. def double(n: int) -> int: return n * 2 The parameter hint goes after the name with a colon; the return hint follows the arrow.
Keep reading to complete this lesson