Chapter 54 of 54

Type Hints in Python

Python is dynamically typed: you never have to say what type a variable holds. That makes small scripts quick to write, but in a big project it becomes hard to answer simple questions like "does this function expect a number or a string?" or "can this return None?"

Type hints let you write that information directly in your code. Your editor and tools can then catch mistakes before you even run the program. They are used in almost every modern Python codebase, including popular frameworks like FastAPI.

What Are Type Hints?

Type hints (also called type annotations) are optional labels that describe the expected types of variables, function parameters and return values. Python itself does not enforce them at runtime.

Here is a function without hints:

def total_price(price, quantity, discount=0.0):
    return price * quantity * (1 - discount)

And the same function with hints:

def total_price(price: float, quantity: int, discount: float = 0.0) -> float:
    return price * quantity * (1 - discount)
  • name: type after a parameter describes that parameter.

  • -> type before the colon describes the return value.

  • A default value comes after the hint: discount: float = 0.0.

Variables can be annotated too:

name: str = "Riya"
age: int = 21
cgpa: float = 8.7
is_placed: bool = False

For simple assignments like these, hints are usually unnecessary because the type is obvious. They are most valuable on function signatures.


Hints Are Not Enforced

This surprises many beginners. Python stores the hints but does not check them when the code runs:

def add(a: int, b: int) -> int:
    return a + b

print(add(2, 3))
print(add("2", "3"))   # wrong types, but Python runs it anyway

Output:

5
23

No error! The hints are information for humans and tools, not rules for the interpreter. To actually catch the mistake, you use a type checker.


Checking Types with mypy

A type checker reads your code (without running it) and reports type mistakes. The most popular ones are mypy and Pyright (which powers the Python support in VS Code). Install mypy with pip:

pip install mypy

Suppose app.py contains:

def add(a: int, b: int) -> int:
    return a + b

def greet(name: str) -> str:
    return "Hello, " + name

total = add(5, "10")
greet(42)
marks: list[int] = [90, 85]
marks.append("A")

Run the checker:

mypy app.py

Output:

app.py:7: error: Argument 2 to "add" has incompatible type "str"; expected "int"  [arg-type]
app.py:8: error: Argument 1 to "greet" has incompatible type "int"; expected "str"  [arg-type]
app.py:10: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"  [arg-type]
Found 3 errors in 1 file (checked 1 source file)

All three bugs are found before the program runs. Your editor shows the same kind of warnings as red underlines while you type, and gives better autocomplete because it knows each variable's type.


Hints for Collections

Use square brackets to say what a collection contains:

scores: list[int] = [90, 85, 77]
marks: dict[str, int] = {"Maths": 95, "CS": 98}
point: tuple[int, int] = (3, 4)
values: tuple[int, ...] = (1, 2, 3, 4)   # any length, all int
tags: set[str] = {"python", "dsa"}

def average(nums: list[float]) -> float:
    return sum(nums) / len(nums)

print(average([8.5, 9.0, 7.5]))

Output:

8.333333333333334

Writing list[int] directly works in Python 3.9 and newer. In older code you will see from typing import List, Dict and List[int], which means the same thing and is now considered outdated.


Optional and Union Types

Sometimes a value can be one of several types. Use the | operator (Python 3.10+):

def find_student(roll: int) -> str | None:
    students = {1: "Asha", 2: "Vikram"}
    return students.get(roll)     # returns None if not found

def to_text(value: int | float) -> str:
    return f"{value:.2f}"

name = find_student(3)
if name is None:
    print("Not found")
print(to_text(5), to_text(2.5))

Output:

Not found
5.00 2.50

str | None clearly warns the caller: "check for None before using this". Older code writes the same idea as Optional[str] or Union[int, float] from the typing module.

A function that returns nothing is annotated with -> None.


Other Useful Hints

Hint

Meaning

Any (from typing)

Any type at all - turns checking off for that value

Callable[[int, int], int] (from collections.abc)

A function taking two ints and returning an int

Iterator[int] (from collections.abc)

An iterator of ints, e.g. a generator function's return type

Literal["asc", "desc"] (from typing)

Only these exact values are allowed

from collections.abc import Callable, Iterator

def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
    return func(a, b)

def countdown(n: int) -> Iterator[int]:
    while n > 0:
        yield n
        n -= 1

print(apply(max, 4, 9))
print(apply(lambda x, y: x * y, 4, 9))
print(list(countdown(3)))

Output:

9
36
[3, 2, 1]

Type Aliases

Long types can be given a short name. Python 3.12 added the type statement for this:

type Marks = dict[str, int]

def topper(marks: Marks) -> str:
    return max(marks, key=lambda name: marks[name])

print(topper({"Asha": 88, "Vikram": 92, "Neha": 79}))

Output:

Vikram

On older versions, a plain assignment works: Marks = dict[str, int].


Generic Functions

What type does a function like "return the first item" return? It depends on the input. A type variable expresses "the same type that came in". Python 3.12 introduced a short syntax with square brackets after the function name:

def first[T](items: list[T]) -> T:
    return items[0]

print(first([10, 20, 30]))       # checker knows this is an int
print(first(["a", "b"]))         # checker knows this is a str

Output:

10
a

Before 3.12 the same thing was written with T = TypeVar("T") from the typing module.


Classes as Types

Any class you create can be used as a type hint:

class Student:
    def __init__(self, name: str, cgpa: float) -> None:
        self.name = name
        self.cgpa = cgpa

def best(students: list[Student]) -> Student:
    return max(students, key=lambda s: s.cgpa)

batch = [Student("Asha", 8.9), Student("Ravi", 9.2)]
print(best(batch).name)

Output:

Ravi

What if a class refers to itself, like a linked list node whose next is another node? From Python 3.14, annotations are evaluated lazily, so this just works. On older versions you must either write the name in quotes ("Node | None") or put from __future__ import annotations at the top of the file.

class Node:
    def __init__(self, value: int, next: "Node | None" = None) -> None:
        self.value = value
        self.next = next

head = Node(1, Node(2, Node(3)))
current: Node | None = head   # may become None at the end
while current is not None:
    print(current.value, end=" ")
    current = current.next
print()

Output:

1 2 3 

The quoted version works on every Python 3 version, so it's the safest choice for code that must run on older interpreters.

Seeing the Hints at Runtime

Python stores hints in the __annotations__ attribute. Tools like FastAPI and Pydantic read them to validate data automatically.

def add(a: int, b: int) -> int:
    return a + b

print(add.__annotations__)

Output:

{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

Which Version Added What?

Feature

Python version

Type hints standard (PEP 484) and the typing module (the annotation syntax itself exists since 3.0)

3.5

Variable annotations (x: int = 5)

3.6

list[int], dict[str, int] without importing from typing

3.9

int | None union syntax

3.10

type aliases and def f[T](...) generics

3.12

Lazy (deferred) evaluation of annotations

3.14


Common Mistakes

  • Thinking hints validate input - add("2", "3") still runs. Use a type checker, or validate explicitly.

  • Forgetting | None - if a function can return None (like dict.get()), say so, otherwise callers forget to check.

  • Overusing Any - it silences the checker and removes the benefit of hints.

  • Mutable default values - def f(items: list[int] = []) is still the shared-default bug from the function arguments chapter. Use items: list[int] | None = None.

  • Using new syntax on old Python - int | None in an annotation fails on 3.9 and earlier unless you use from __future__ import annotations.


Interview Tips

  • Does Python enforce type hints? No. They are ignored at runtime; tools like mypy and Pyright check them statically.

  • Is Python still dynamically typed with hints? Yes. Hints add optional static checking on top of dynamic typing (often called gradual typing).

  • Benefits: early bug detection, better IDE autocomplete, self-documenting code, safer refactoring in large teams.

  • Practice: add full type hints to three functions you wrote in earlier chapters and run mypy on them until it reports no errors.

Summary

  • Annotate parameters with name: type and return values with -> type.

  • Hints are not enforced at runtime; use mypy, Pyright or your IDE to check them.

  • Use list[int], dict[str, int], tuple[int, ...] for collections and X | None for optional values.

  • Use Callable, Iterator, aliases and generics for more precise hints.

Type hints don't change how Python runs your code - they change how easily you, your teammates and your tools can understand and trust it.