Module 6 · Beginner · Functions and modules

Python type hints for beginners

Python type hints for beginners: annotating functions, list[int] and dict[str, float], optional values with | None, type aliases and checking with mypy.

By theprogrammers team · · 9 min read

You find a function written by a classmate: def calculate(data, rate, flag). What is data, a list or a dictionary? Is rate 18 or 0.18? What does it return? You'd have to read the whole function, or run it and see what breaks. Python type hints answer those questions in the first line: def calculate(data: list[float], rate: float, flag: bool) -> float.

Type hints are labels that say what type each variable, parameter and return value should be. Python itself doesn't enforce them, which surprises everyone. But your editor uses them to catch mistakes as you type, and tools like mypy check a whole project before you run it. Almost every modern library, and FastAPI and Pydantic in particular, is built around them.

What you need first: Python functions and Python variables and data types.

Key terms

  • Type hint (annotation): a note in the code saying what type a value should be, like marks: int.
  • Return type: the type a function gives back, written after ->.
  • Type checker: a separate tool, such as mypy or Pyright, that reads your hints and reports mismatches without running the code.
  • Union type: a value that can be one of several types, written int | str.
  • Optional: a value that can be a given type or None, written str | None.

Your first type hints

Add : type after a parameter and -> type before the colon to give the return type:

def price_with_gst(price: float, rate: float = 0.18) -> float:
    return round(price * (1 + rate), 2)

print(price_with_gst(1000))
1180.0

Read it as: "price_with_gst takes a price that's a float and a rate that's a float (0.18 by default), and returns a float."

Variables can have hints too, though you rarely need them because the type is obvious from the value:

name: str = "Ahana"
marks: int = 88
passed: bool = marks >= 40
print(name, marks, passed)
Ahana 88 True

A function that returns nothing is marked -> None:

def greet(name: str) -> None:
    print(f"Hello, {name}")

greet("Rohan")
Hello, Rohan

Python doesn't enforce type hints

This is the part to remember. Hints are notes, not rules. Python runs this happily:

def double(n: int) -> int:
    return n * 2

print(double("ha"))
haha

The hint says int, we passed a string, and Python didn't complain, because "ha" * 2 is valid. Python stores the hints but never checks them while running:

def double(n: int) -> int:
    return n * 2

print(double.__annotations__)
{'n': <class 'int'>, 'return': <class 'int'>}

So what are they for? Three things:

  1. Readers see what a function expects without reading its body.
  2. Your editor (VS Code, PyCharm) uses them for autocomplete and underlines mistakes in red as you type.
  3. Type checkers like mypy check the whole project and catch bugs such as passing a string where a number is needed, before the code ever runs.

Hints for collections

Since Python 3.9, you can write the item type inside square brackets on the built-in types:

HintMeansExample value
list[int]A list of ints[72, 88, 95]
tuple[float, float]A tuple of exactly two floats(18.92, 72.83)
tuple[int, ...]A tuple of any number of ints(1, 2, 3, 4)
dict[str, float]A dict with str keys and float values{"tea": 20.0}
set[str]A set of strings{"Pune", "Goa"}
def average(marks: list[int]) -> float:
    return sum(marks) / len(marks)

def cheapest(menu: dict[str, float]) -> str:
    return min(menu, key=menu.get)

def location() -> tuple[float, float]:
    return 18.92, 72.83

print(average([72, 88, 95]))
print(cheapest({"tea": 20.0, "samosa": 15.0}))
print(location())
85.0
samosa
(18.92, 72.83)

In older code (Python 3.8 and before) you'll see List[int] and Dict[str, float] imported from the typing module. They mean the same thing. Use the lower-case built-in versions in new code.

Optional values and unions

Many functions can return "nothing found". In Python that's None, and the hint says so with | None:

def find_roll(names: list[str], wanted: str) -> int | None:
    for i, name in enumerate(names):
        if name == wanted:
            return i + 1
    return None

print(find_roll(["Ahana", "Rohan"], "Rohan"))
print(find_roll(["Ahana", "Rohan"], "Meera"))
2
None

int | None reads "an int or None". It needs Python 3.10 or newer. Older code writes the same thing as Optional[int] or Union[int, None] from typing.

The hint is a warning to the caller: "check for None before using this". A type checker will flag code like find_roll(names, x) + 1, because adding 1 to None would crash.

Use | for any mix of types:

def to_rupees(amount: int | float | str) -> str:
    return f"₹{float(amount):,.2f}"

print(to_rupees(1250), to_rupees(99.5), to_rupees("100000"))
₹1,250.00 ₹99.50 ₹100,000.00

Python's , format groups digits in thousands, so one lakh prints as 100,000, not 1,00,000. Indian-style grouping needs extra code.

Other useful hints

HintUse it for
Any (from typing)Anything at all; switches checking off for that value
Callable[[int], str] (from collections.abc)A function that takes an int and returns a str
Iterable[str] (from collections.abc)Anything you can loop over that gives strings
Literal["asc", "desc"] (from typing)Only these exact values

For parameters, a general type like Iterable[str] is often better than list[str], because it also accepts tuples, sets and generators:

from collections.abc import Iterable

def total_length(words: Iterable[str]) -> int:
    return sum(len(w) for w in words)

print(total_length(["data", "science"]), total_length(("ai", "ml")))
11 4

Type aliases

Long hints get repetitive. Give them a name:

Point = tuple[float, float]

def distance(a: Point, b: Point) -> float:
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

print(distance((0, 0), (3, 4)))
5.0

Python 3.12 added a dedicated syntax, type Point = tuple[float, float], which does the same thing.

Checking types with mypy

mypy is the original Python type checker. It's a separate package, so installing it is up to you; see pip and virtual environments for how. Once installed, you run it on a file from the terminal:

pip install mypy
mypy marks.py

If marks.py calls double("ha") from the example above, mypy reports an error on that line saying the argument has type str where int was expected, and nothing runs. In VS Code, the Python extension's Pylance checker shows similar warnings as you type; set "Type Checking Mode" to "basic" in settings to turn them on.

You don't have to add hints everywhere at once. mypy only checks functions that have hints, so you can add them a file at a time.

Where type hints are used

  • FastAPI reads your hints to check incoming web requests and to write API documentation automatically.
  • Pydantic uses hints to validate data, turning "42" into 42 or raising a clear error.
  • Dataclasses use hints to define fields; they're covered in the object-oriented module.
  • Large codebases at most companies that use Python run a type checker in their test process, so hints are expected in professional code.

Common mistakes

  • Expecting Python to stop bad types at run time. It won't; use a type checker or explicit checks.
  • -> None on a function that returns a value, or forgetting | None on one that sometimes returns None.
  • list[int] on Python 3.8 or older, which raises TypeError: 'type' object is not subscriptable. Upgrade, or use typing.List.
  • Overusing Any. It silences the checker, so you lose the benefit.
  • Hints that lie. A wrong hint is worse than none, because readers trust it.

Practice

  1. Add type hints to this function.
def full_name(first, last, middle=""):
    return f"{first} {middle} {last}".replace("  ", " ")
Show the answer
def full_name(first: str, last: str, middle: str = "") -> str:
    return f"{first} {middle} {last}".replace("  ", " ")

print(full_name("Ahana", "Khan"))
Ahana Khan
  1. Write the hint for each: a list of prices with decimals; a dictionary from roll numbers to names; a tuple of (name, age).
Show the answer

list[float], dict[int, str] and tuple[str, int].

  1. Write safe_divide(a: float, b: float) that returns None when b is 0, with the correct return hint.
Show the answer
def safe_divide(a: float, b: float) -> float | None:
    if b == 0:
        return None
    return a / b

print(safe_divide(10, 4), safe_divide(10, 0))
2.5 None
  1. Does this code raise an error when run? What would mypy say?
def add(a: int, b: int) -> int:
    return a + b

print(add(2.5, 1.5))
Show the answer

It runs and prints 4.0, because Python ignores hints at run time. mypy would report an error, because 2.5 is a float and the hint asks for int. (Going the other way is allowed: you can pass an int where a float is expected.)

  1. Write a function word_lengths(words) with hints, which takes any iterable of strings and returns a dictionary from each word to its length.
Show the answer
from collections.abc import Iterable

def word_lengths(words: Iterable[str]) -> dict[str, int]:
    return {w: len(w) for w in words}

print(word_lengths(("tea", "coffee")))
{'tea': 3, 'coffee': 6}

Interview questions

Does Python enforce type hints at run time?

No. Python stores annotations (you can read them from __annotations__) but doesn't check them. Static checkers such as mypy or Pyright, or libraries like Pydantic, do the checking.

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

They mean the same thing: an int or None. int | None is the newer syntax from Python 3.10 (PEP 604); Optional[int] from typing works on older versions.

Why use type hints if Python ignores them?

They document intent, power editor autocomplete and error highlighting, and let static checkers find whole classes of bugs before the code runs. Frameworks like FastAPI and Pydantic also use them to validate data.

Key takeaways

  • Write param: type for parameters and -> type for the return value.
  • Python doesn't enforce hints; editors and checkers like mypy use them to find bugs early.
  • Use list[int], dict[str, float] and tuple[float, float] for collections (Python 3.9+).
  • X | None marks values that can be missing; callers should check for None.
  • Add hints gradually, starting with function signatures.

Frequently asked questions

Do type hints make Python faster?

No. Standard Python ignores them when running code. Some separate tools, such as mypyc, can use them to compile faster code, but that's an advanced use.

Should beginners use type hints?

Yes, on function parameters and return values. They make you think about what each function takes and gives back, and your editor will catch more mistakes. You don't need them on every variable.

Which Python version do I need for type hints?

Basic hints work on Python 3.5 and later. list[int] needs 3.9, int | None needs 3.10, and the type alias statement needs 3.12. A current version of Python supports all of them.

What to learn next

  1. Split a growing project into files in Python modules and packages.
  2. Install tools like mypy safely with pip and virtual environments.
  3. Revise function basics in Python functions.