TExcelTAD
Home › Python › Python Type Hints

Python Type Hints

Python is dynamically typed: variables don't have declared types. Since Python 3.5, though, you can add optional type hints (annotations) that say what types you expect. Python itself ignores them at runtime, but editors use them for autocompletion and error highlighting, and tools such as mypy and pyright use them to find bugs before your code runs.

Annotating functions and variables

Put : type after a parameter or variable and -> type after the parameter list for the return value:

python · try it yourself
def greet(name: str, times: int = 1) -> str:
    return ", ".join([f"Hello {name}"] * times)

count: int = 3
ratio: float = 0.5
print(greet("Quyen", 2))
print(greet.__annotations__)
Hello Quyen, Hello Quyen
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}

The hints are stored in __annotations__, but nothing checks them while the program runs:

python · try it yourself
def double(n: int) -> int:
    return n * 2

print(double("ha"))     # no error at runtime - a type checker would complain
haha

Note: Type hints are documentation that tools can verify. To actually enforce types at runtime you'd use isinstance checks or a library such as pydantic.

Collection types

Since Python 3.9 you can use the built-in collection types directly with square brackets:

Hint Means
list[int] a list of ints
dict[str, float] dict with str keys and float values
tuple[int, int] a tuple of exactly two ints
tuple[str, ...] a tuple of any number of strs
set[str] a set of strings
python · try it yourself
def average(scores: list[float]) -> float:
    return sum(scores) / len(scores)

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

def bounds(values: list[int]) -> tuple[int, int]:
    return min(values), max(values)

print(average([7.5, 9.0, 8.5]))
print(word_lengths(["sun", "river"]))
print(bounds([4, 1, 9]))
8.333333333333334
{'sun': 3, 'river': 5}
(1, 9)

Optional values and unions

When a value may be one of several types, use | (Python 3.10+). X | None means "an X or nothing" — very common for results that might be missing:

python · try it yourself
def find_user(user_id: int) -> str | None:
    users = {1: "Ha", 2: "Kien"}
    return users.get(user_id)

def parse(value: int | str) -> int:
    return value if isinstance(value, int) else int(value)

print(find_user(2), find_user(9))
print(parse(5) + parse("7"))
Kien None
12

On Python 3.9 and earlier, write Optional[str] and Union[int, str] from the typing module instead.

The typing module

Tool Use
Any opt out of checking for one value
Callable[[int, int], int] a function taking two ints, returning int
Iterable[str], Iterator[int] anything you can loop over
TypeAlias / simple assignment give a long type a name
TypedDict a dict with fixed keys and value types
Protocol "any object with these methods" (duck typing)
Literal["r", "w"] only these exact values
python · try it yourself
from typing import Callable, Iterable, TypedDict

Vector = list[float]          # a type alias

def scale(v: Vector, k: float) -> Vector:
    return [x * k for x in v]

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

def total(items: Iterable[int]) -> int:
    return sum(items)

class Movie(TypedDict):
    title: str
    year: int

m: Movie = {"title": "Spirited Away", "year": 2001}
print(scale([1.0, 2.5], 2))
print(apply(lambda x, y: x * y, 6, 7))
print(total(range(5)), total({1, 2}))
print(m["title"], m["year"])
[2.0, 5.0]
42
10 3
Spirited Away 2001

Hints on classes

Type hints work naturally with your own classes and are what make dataclasses so concise:

python · try it yourself
from dataclasses import dataclass

@dataclass
class Task:
    title: str
    done: bool = False

def pending(tasks: list[Task]) -> list[str]:
    return [t.title for t in tasks if not t.done]

todo = [Task("write tests"), Task("fix bug", done=True), Task("deploy")]
print(pending(todo))
['write tests', 'deploy']

Checking hints with mypy

A type checker reads your code without running it. After pip install mypy, it finds mistakes like the double("ha") call above:

bash · try it yourself
mypy app.py
app.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Tip: Add hints gradually — start with function signatures in the code you share with others. Even partial hints make editors much more helpful.

Test yourself

What happens at runtime if you pass a str to a parameter hinted as int?

  1. TypeError is raised
  2. The value is converted to int
  3. Nothing - hints are not enforced at runtime
  4. A warning is printed

Which hint means "a string or None" in Python 3.10+?

  1. str?
  2. str | None
  3. Optional(str)
  4. str or None

How do you annotate a function's return type?

  1. def f() : int
  2. def f() -> int:
  3. def f() returns int:
  4. int def f():