Type hints are optional labels that say what type of data a variable, parameter, or return value should hold, like pages: int or -> float. Python doesn’t enforce them when the code runs, but editors use them for autocomplete and warnings, and type checkers like mypy use them to find bugs before you run anything.

Python is dynamically typed: a variable can hold a number now and text later, and nothing stops you from passing the wrong kind of value to a function until it breaks, sometimes far from the real mistake. Type hints, added in Python 3.5 and much improved since, let you write down your intentions so tools can check them. Modern libraries like FastAPI and Pydantic even use them to validate data.

This guide covers the type hints you’ll use day to day, how to check them with mypy, and when they’re worth adding. Every example was run with Python 3.12 and mypy, and the outputs shown are real. It assumes you know functions and classes.

Your First Type Hints

Here’s a function from the functions lesson, with hints added. pages: int says the parameter should be an integer, and -> float says what the function returns:

HOURLY_RATE = 85


def calculate_quote(pages: int, rush: bool = False) -> float:
    total = pages * 4 * HOURLY_RATE
    if rush:
        total = total * 1.25
    return total


print(calculate_quote(5))
print(calculate_quote("5"))

Run it, and both calls “work”:

1700
5555555555555555555555555555555555555555...

The second call passed the text "5", and Python happily repeated the string, producing a 340-character string of fives instead of a price. Type hints didn’t stop it: Python ignores them at runtime. Their power comes from tools that read them.

Catch Bugs With mypy

mypy is the most widely used type checker. Install it in your virtual environment and point it at your file:

python -m pip install mypy
python -m mypy quote.py
quote.py:7: error: Incompatible types in assignment (expression has type "float", variable has type "int")  [assignment]
quote.py:12: error: Argument 1 to "calculate_quote" has incompatible type "str"; expected "int"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

mypy found the bad call on line 12 without running the code. It also found something subtle on line 7: total starts as an integer (pages * 4 * 85), then becomes a decimal when multiplied by 1.25. mypy infers a variable’s type from its first value, so you tell it the variable is meant to hold a float:

HOURLY_RATE = 85


def calculate_quote(pages: int, rush: bool = False) -> float:
    total: float = pages * 4 * HOURLY_RATE
    if rush:
        total = total * 1.25
    return total


print(calculate_quote(5))
print(calculate_quote(5, rush=True))
1700
2125.0

Now python -m mypy quote.py reports Success: no issues found in 1 source file.

The Basic Types

from collections.abc import Callable

name: str = "Bakery Lopez"
pages: int = 6
rate: float = 85.0
is_rush: bool = False
services: list[str] = ["design", "hosting"]
prices: dict[str, float] = {"design": 1500.0, "hosting": 25.0}
point: tuple[float, float] = (32.79, -115.56)
discount: float | None = None


def apply(price: float, rule: Callable[[float], float]) -> float:
    return rule(price)


print(apply(100.0, lambda p: p * 0.9))
HintMeaning
int, float, str, boolThe basic types
list[str]A list of strings
dict[str, float]A dictionary with string keys and float values
tuple[float, float]A tuple of exactly two floats
set[int]A set of integers
float | NoneA float or None (often called “optional”)
int | strAn integer or a string
Callable[[float], float]A function that takes a float and returns a float
AnyAnything; turns off checking for that value

The | syntax for “either type” works in Python 3.10 and later. Older code writes the same ideas as Optional[float] and Union[int, str], imported from typing, and List[str] with a capital L. They mean the same thing.

You rarely need to annotate simple variables, since pages = 6 is obviously an int and type checkers figure that out. Focus on function parameters and return values, where the hints document how to use your code.

Classes, None, and Literal

Type hints shine on data structures. Here a dataclass describes a project, Literal limits status to three exact values, and a function may return a project or None:

from dataclasses import dataclass
from typing import Literal

Status = Literal["planned", "active", "done"]


@dataclass
class Project:
    client: str
    budget: float
    status: Status = "planned"
    tags: list[str] | None = None


def total_budget(projects: list[Project]) -> float:
    return sum(p.budget for p in projects)


def find_project(projects: list[Project], client: str) -> Project | None:
    for project in projects:
        if project.client == client:
            return project
    return None


projects = [Project("Bakery Lopez", 2400), Project("Garcia Law", 600, "active")]
print(total_budget(projects))

found = find_project(projects, "Garcia Law")
print(found.status.upper())

projects.append(Project("Valley Fitness", 900, "finished"))

This runs without errors and prints 3000 and ACTIVE, but mypy finds two real problems:

projects.py:30: error: Item "None" of "Project | None" has no attribute "status"  [union-attr]
projects.py:32: error: Argument 3 to "Project" has incompatible type "Literal['finished']"; expected "Literal['planned', 'active', 'done']"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)
  1. find_project() can return None, for example when the client name is misspelled. Then found.status would crash with AttributeError. mypy makes you handle that case.
  2. "finished" isn’t an allowed status. Without Literal, that typo would silently create a project that no report ever counts as done.

The fix is a None check and the right value:

if found is not None:
    print(found.status.upper())

projects.append(Project("Valley Fitness", 900, "done"))

After that, mypy reports no issues. These are exactly the kinds of bugs that otherwise show up in production, as covered in Debugging Python.

Type Hints in Your Editor

You don’t have to run mypy to benefit. VS Code with the Python extension (which includes the Pylance language server) uses type hints to:

  • Autocomplete methods and attributes: type found. and it lists client, budget, status, and tags.
  • Show function signatures as you type a call, including parameter types.
  • Underline problems as you type. Set Python > Analysis: Type Checking Mode to basic or standard in the settings to see type errors right in the editor.

How to Add Type Hints to a Project

  1. Start with new code. Annotate the functions you write from now on.
  2. Annotate function signatures first. Parameters and return values give the most value for the least effort.
  3. Run mypy regularly, or add it to your tests and CI. Add python -m mypy . next to pytest in your workflow (see Testing Your Code).
  4. Tighten gradually. mypy skips functions without hints by default. Once most of the code is annotated, options like --strict check everything.
  5. Install type stubs when mypy asks for them, for libraries that ship their types separately, like types-requests for requests.

Common Mistakes to Avoid

  • Expecting Python to enforce hints. It doesn’t. Use mypy or your editor, or Pydantic when you need checks at runtime.
  • Using Any everywhere. It silences the checker. Use it sparingly, for truly dynamic data.
  • Forgetting None. If a function can return None, say so with | None, and handle it where you call it.
  • Annotating list without the item type. list[str] tells tools much more than list.
  • Mutable default values. Hints don’t fix the classic def f(items: list[str] = []) bug; use None as the default.

Frequently Asked Questions

Do type hints make Python faster?

No. Standard Python ignores them when running. Their value is catching bugs earlier and making code easier to read and use.

Are type hints required?

No, they’re completely optional. Small scripts often don’t need them. They pay off in larger projects, shared code, and anything that will be maintained for a while.

mypy or Pyright?

Both are good type checkers. mypy is the original command-line tool; Pyright powers VS Code’s Pylance and is very fast. Many developers use Pylance in the editor and mypy in tests and CI.

What’s the difference between Optional[int] and int | None?

Nothing; they mean the same thing. int | None is the newer, shorter spelling, available since Python 3.10.

Conclusion

Type hints let you write down what your code expects, pages: int, -> float, list[str], Project | None, so your editor and a type checker can catch mistakes before they become bugs. Python itself ignores them, so pair them with mypy or VS Code’s type checking. Start by annotating function parameters and return values in new code, handle None explicitly, use Literal for fixed choices, and run mypy alongside your tests.