All concepts

Type Hints

Annotate types so checkers catch bugs before runtime; frameworks read them too.

Python · Beginner · ~5 min

In plain English

Notes in the code saying what shape each value is meant to be. Python ignores them at runtime; your editor and your type checker do not.

Why it's worth your time

On any codebase touched by more than one person, they catch a whole class of bug before it ever runs.

If you remember three things

  • Not enforced at runtime — they're for tooling and readers
  • Optional[X] means it can be None, and that's usually the bug
  • Public function signatures are where they pay the most

Overview

Type hints annotate parameters, returns, and variables with expected types. The typing vocabulary adds container shapes (list[int]), optionals (Optional[X]), and unions (A | B). Static checkers like mypy and pyright use them to catch bugs before runtime; Python itself ignores them at runtime, but libraries like Pydantic and FastAPI read them.

In an interview

Type hints document the types of parameters, returns, and variables so a static checker—mypy or pyright—can flag mismatches in your editor or CI before the code runs. They're purely optional and Python ignores them at runtime, so there's no performance cost and no automatic enforcement. Their real leverage today is that frameworks read them: Pydantic validates data from hints and FastAPI generates validation and docs from them.

Production defaults

Annotate
every public function's arguments and return. Internal helpers are optional
Check
mypy or pyright in CI. Unchecked hints drift into fiction
Runtime validation
hints don't validate. Use Pydantic where the data comes from outside

What breaks

  • Hints say one thing, data is another — They're not enforced. Add a type checker to CI, and validate external data with Pydantic.
  • NoneType has no attribute… — An Optional you didn't narrow. The checker would have flagged it.

Watch it explained

The BIGGEST Misconception About Type Hints In Python Explained — Indently, 5:14

Related