Skip to content
Forge Learn/Modern Python Tooling

Type Hints & Static Typing

5 min read

You'll learn to

  • -Annotate function parameters and return values with type hints
  • -Explain what type hints do (and do not) do at runtime
  • -Use builtin generics like `list[int]` and know where `typing` imports are unavailable in this course's lab

Every function you have written so far works without ever stating what type its parameters or return value are - Python figures it out dynamically at runtime. Type hints let you write that information down explicitly anyway, purely for the benefit of humans and tools reading the code, not because Python requires it.

Basic Type Hint Syntax

Type hints on parameters and return values

Type hints are not enforced at runtime. `add("a", "b")` will happily run and return `"ab"` even though the hint says `int` - Python does not check hints as your code executes. Their value comes entirely from readability and from external tools (editors, linters like mypy) that read them and warn you about mismatches before you run anything.

Why Bother, If Python Doesn't Enforce Them?

Type hints turn a function signature into documentation that cannot silently drift out of date the way a comment can. They also let your editor autocomplete correctly, catch a whole class of "passed the wrong type" bugs before you ever run the code, and make large codebases dramatically easier to navigate - you can see what a function expects and returns without reading its body.

Optional and Builtin Generics

The `typing` module historically provided helpers like `Optional[int]` (meaning "an `int`, or `None`") and `List[int]`. Modern Python (3.9+) lets you use the builtin container types directly as generics - `list[int]`, `dict[str, int]` - without any import at all, and the `| None` union syntax (3.10+) replaces `Optional`.

typing.Optional vs. the modern builtin-generic style

Heads up for this course: the Forge Algorithm Lab's code sandbox restricts imports to a safe allowlist for security, and `typing` is not on it. That only affects code you submit to the lab, though - hints written with bare builtin generics like `list[int]`, `dict[str, int]`, and the `| None` union syntax need no import at all, so they work fine inside lab submissions. `from typing import Optional` specifically would not.

  • -Type hints document expected types; Python does not check or enforce them at runtime.
  • -Prefer builtin generics (`list[int]`, `dict[str, int]`) and `X | None` over importing from `typing` where possible - shorter, and importable everywhere including the Forge Algorithm Lab sandbox.
  • -External tools (mypy, your editor) are what actually make hints useful, by flagging mismatches before you run the code.
ScaleDojo Logo
Initializing ScaleDojo