Skip to content
Visual explainer 2h to learn 4 steps

Type hints

Annotate functions and classes so editors and type checkers catch mistakes.

By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.

Topic 24 of 34

In short

Type hints label what types a function expects and returns. Python ignores them when running, but editors and type checkers like mypy or Pyright read them to catch mistakes before you run the code.

Explained simply

A type hint is a small label in your code that says what kind of value is expected. In def total(prices: list[float]) -> float, the hints say: give me a list of floats, and I give back a float. They are like the labels on the sockets of a machine: they do not stop you plugging in the wrong cable, but they make it obvious.

Python itself ignores the hints when it runs your code. The value comes from tools that read them. Your editor uses them to suggest the right methods and to underline mistakes as you type. A type checker such as mypy or Pyright reads the whole project and reports every place where the types do not fit.

The most common bug they catch is None. A function that can return either a user or None is written -> User | None. If you then call .name on the result without checking, the checker warns you before a user ever sees a crash.

You can add hints step by step. Start with the function signatures that other code calls, run a checker, and fix what it reports. Every hint you add makes the next change a little safer.

Press Play on a diagram to walk through it one step at a time.

FlowWhere type hints help
  1. 1
    Annotate code

    def total(prices: list[float]) -> float

  2. 2
    Editor reads hints

    Better autocomplete and inline warnings

  3. 3
    Run mypy / Pyright

    Checks every call against the hints

  4. 4
    Fix reported errors

    Before users ever hit them

  5. 5
    Python runs

    Hints are not enforced at runtime

MapChoosing a hint
What is the value?
  • A simple value
    • int, str, float, bool
    • Literal["a", "b"] for fixed constants
  • Maybe missing
    • X | None
    • Check for None before use
  • A collection
    • list[int], set[str]
    • dict[str, float]
    • tuple[str, int]
  • Something you only loop over
    • Iterable[T] for parameters
    • Sequence[T] if you index it
  • A record
    • @dataclass fields
    • TypedDict for dict-shaped JSON

In depth

What hints are at runtime

Hints are stored on the function in __annotations__ and can be read with typing.get_type_hints(f), which is how libraries like dataclasses, Pydantic and FastAPI use them. Python does not check them: total("pen") still runs and fails, or worse, succeeds with a wrong result. That is why you pair hints with a checker.

Hints cost almost nothing at runtime. Older code sometimes starts with from __future__ import annotations, which stores hints as strings and lets a class refer to itself before it is fully defined. Since Python 3.14, annotations are evaluated lazily by default (PEP 649), which solves the same forward-reference problem without the import. If you need real runtime validation of outside data, such as JSON from an API, use a library such as Pydantic that reads the hints and checks values.

The vocabulary you need first

Built-in types work as hints: int, str, float, bool, bytes. Containers take their item types in square brackets (Python 3.9+): list[int], set[str], dict[str, float]. Tuples list each position, tuple[str, int], or use tuple[int, ...] for any length. X | None (Python 3.10+, same as Optional[X]) means the value may be missing. A | B means either type.

For parameters, accept the widest thing you actually need. If a function only loops over its input, hint it as Iterable[str] from collections.abc, so callers can pass a list, a set or a generator. If it needs indexing, use Sequence. Return the concrete type you build, like list[str]. Use Any only as a last resort: it switches checking off for that value. Literal["r", "w"] restricts a value to exact constants, and Callable[[int], str] describes a function argument.

  • def first(xs: Sequence[str]) -> str | None:
  • def load(mode: Literal["r", "w"]) -> None:
  • def apply(f: Callable[[int], int], x: int) -> int:
  • type UserId = int (alias syntax, Python 3.12+)

Narrowing: how checkers follow your if statements

Type checkers do not just read signatures; they track what each variable can be at each line. If name has type str | None, calling name.upper() is an error, because None has no upper method. After if name is None: return, the checker knows name is a str for the rest of the function. This is called narrowing.

isinstance(x, int), truthiness checks like if name:, early returns and raising all narrow types. When you are unsure what the checker thinks, write reveal_type(x) and run the checker; it prints the inferred type. Avoid silencing errors with cast() or # type: ignore unless you truly know better than the checker; if you must ignore, add the specific error code, like # type: ignore[union-attr], so other problems on that line still show.

FlowHow a checker narrows str | None
  1. Step 1
    name = find(uid)

    Type is str | None

  2. Step 2
    name.upper()

    Error: None has no attribute upper

  3. Step 3
    if name is None: return

    The None case leaves the function

  4. Step 4
    name.upper()

    OK: name is now known to be str

Typing classes and dataclasses

In methods, leave self unannotated; checkers know what it is. Annotate the other parameters and the return as usual. For a classmethod that builds an instance, return typing.Self (Python 3.11+) so subclasses get the right type. A method that returns nothing is -> None.

Dataclasses are typed by design: each field already has a hint, so checkers verify Order(id="x") calls for free. To mark a class-level constant that should not become a dataclass field, annotate it with ClassVar[int]. For a value that must never be reassigned, use Final. When a plain dict has a fixed shape, for example parsed JSON, TypedDict describes its keys and value types without turning it into a class.

  • def from_row(cls, row: dict[str, str]) -> Self:
  • MAX_ITEMS: ClassVar[int] = 50 inside a dataclass
  • class Movie(TypedDict): title: str; year: int

Running mypy or Pyright on a project

Install a checker in the project's venv: pip install mypy, then run mypy src/ (or mypy . for a small project). Clean output is Success: no issues found in N source files. Errors look like app.py:12: error: Argument 1 to "total" has incompatible type "str"; expected "list[Item]" [arg-type]. Pyright is the engine behind VS Code's Pylance extension, so you may already see its warnings; run it in the terminal with pip install pyright, then pyright.

One important default: mypy does not check the bodies of functions that have no annotations at all. Add check_untyped_defs = true under [tool.mypy] in pyproject.toml, or aim for mypy --strict on new code. For third-party packages without built-in hints, install their stub packages, such as types-requests. Run the checker in CI next to your tests so new code stays typed.

Comparemypy vs Pyright
mypy
  • pip install mypy; mypy src/
  • Config: [tool.mypy] in pyproject.toml
  • Skips unannotated function bodies by default
  • --strict for full checking
Pyright
  • pip install pyright; pyright
  • Config: [tool.pyright] in pyproject.toml
  • Infers and checks unannotated code too
  • Powers Pylance in VS Code

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Annotate function parameters and returns~30m
  2. 2
    Use list, dict and Optional hints~30m
  3. 3
    Type a dataclass~30m
  4. 4
    Run mypy or Pyright on a project~30m

Key points

  • Annotate parameters with name: type and returns with -> type.
  • Use built-in generics: list[int], dict[str, float], tuple[int, int].
  • int | None (or Optional[int]) means the value may be None.
  • Dataclass fields are already annotated, so checkers understand them for free.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    price: float

def total(items: list[Item], discount: float | None = None) -> float:
    subtotal = sum(i.price for i in items)
    if discount is None:
        return subtotal
    return subtotal * (1 - discount)

print(total([Item("pen", 2.5)]))
total("pen")  # mypy: incompatible type "str"; runtime: crashes later

The checker finds a None bug

find_user can return None when the id is unknown. Step 1: greet calls .upper() on the result without checking. Step 2: mypy reports the exact line and the reason. Step 3: handle the None case first; after the early return, the checker narrows name to str and the error disappears. At runtime the old version would have crashed only for unknown users, the kind of bug that slips through manual testing.

python
def find_user(users: dict[int, str], uid: int) -> str | None:
    return users.get(uid)

def greet(users: dict[int, str], uid: int) -> str:
    name = find_user(users, uid)
    return "Hello " + name.upper()
# mypy: error: Item "None" of "str | None" has no attribute "upper"  [union-attr]

def greet_fixed(users: dict[int, str], uid: int) -> str:
    name = find_user(users, uid)
    if name is None:
        return "Hello stranger"
    return "Hello " + name.upper()

A typed dataclass with an alternative constructor

Step 1: the dataclass fields carry the types. Step 2: from_row returns Self, so a subclass would get its own type back. Step 3: total accepts any Iterable[Expense], so a list, a tuple or a generator all work. Step 4: run mypy --strict expenses.py. If you write total(["12"]), mypy reports a list item of the wrong type before the code ever runs.

python
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Self

@dataclass
class Expense:
    amount: float
    category: str

    @classmethod
    def from_row(cls, row: dict[str, str]) -> Self:
        return cls(float(row["amount"]), row["category"])

def total(items: Iterable[Expense]) -> float:
    return sum(e.amount for e in items)

Quick reference

  • def f(name: str, tries: int = 3) -> bool: is the basic signature form
  • list[int], dict[str, float], tuple[str, int] work directly since Python 3.9
  • X | None means optional (3.10+); check for None before using the value
  • Accept Iterable or Sequence in parameters; return concrete types like list
  • reveal_type(x) makes the checker print what it thinks x is
  • mypy skips unannotated functions unless check_untyped_defs = true or --strict
  • Hints are not enforced at runtime; use Pydantic to validate outside data

Common mistakes

  • Assuming hints validate data at runtime; they do not.
  • Using Any everywhere, which switches checking off.
  • Forgetting to handle None when a hint says the value is optional.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1def f(x: int) -> int: return x * 2. What does f("ab") do when run with plain python?

Question 2

2A function only loops over its argument. Which parameter hint is most flexible?

Question 3

3You run mypy on a file where no function has any annotations. Typical result?

Question 4

4How do you hint a function that returns a list of strings or None?

Question 5

5What does reveal_type(x) do?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add type hints to: def average(nums): return sum(nums) / len(nums) if nums else None

  2. Exercise 2medium

    Write and type word_index(lines) that maps each word to the sorted list of line numbers where it appears. Run mypy --strict on it.

  3. Exercise 3hard

    Write a generic function first(items, default) that returns the first item of a sequence or the default, so that first([1, 2], 0) is int and first(["a"], "") is str for the checker.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do type hints make Python faster?
No. Standard CPython ignores them when running. Tools like mypyc can compile typed code, but that is a separate step.
Should I use List[int] from typing or list[int]?
Use list[int]. The capitalised versions from typing are older and deprecated aliases; built-in generics work since Python 3.9.
mypy or Pyright: which should I use?
Both are good. If you use VS Code, Pyright (through Pylance) already runs as you type; mypy is the long-standing standard in many CI setups. Pick one per project and run it in CI.
Do I need to annotate every variable?
No. Checkers infer most local variable types from their values. Annotate function signatures, and only add variable hints when inference cannot work, like an empty dict you fill later.

Go deeper

ShareXLinkedInWhatsApp