Type Hints & Static Typing
Published by Brayan K
Modern Python development increasingly depends on static typing — not to replace Python's dynamic nature, but to catch bugs earlier, write clearer APIs, and scale large codebases safely. If you understand type hints deeply, your Python code becomes easier to refactor, safer to modify, more readable, better documented, and more compatible with modern IDE autocompletion.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A hint is a note: Python doesn't check it or convert the value
This lesson writes type hints, shows what Python does with them, and runs mypy, the program that checks them. Two lessons go further: Advanced Type Hints (Generics, Protocol, TypedDict) for the hints this lesson only previews, and Static Type Checking with mypy for setting mypy up across a whole project.
A hint goes after a parameter's name, a: int, and after the brackets for what the function returns, -> int. It says which type the value should have. Python doesn't check it: the same function adds two strings, or two lists, without a word.
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))
print(add("2", "3"))
print(add([1], [2]))
# ✅ Expected output:
# 5
# 23
# [1, 2]It doesn't convert a value to the hinted type either. A string stays a string, so doubling it repeats it. Text from input() is always a string, and only int() turns it into a number:
def double(n: int) -> int:
return n * 2
typed = "21"
print(double(typed))
print(double(int(typed)))
# ✅ Expected output:
# 2121
# 42When a wrong type does stop the program, the error comes from the line in the body that can't use the value, not from the hint:
def add_vat(price: float) -> float:
return price * 1.2
print(add_vat(10))
print(add_vat("10"))
# ✅ Expected output:
# 12.0
# ✅ Expected error:
# TypeError: can't multiply sequence by non-int of type 'float'mypy reads the hints and checks the program before it runs
mypy is a separate program that reads your code without running it and checks it against the hints. It runs on your computer, not in this site's Run button. Install it once, then give it a file:
python -m pip install mypy
mypy shop.pySaved as shop.py, the last example gives one line for its one problem, then a summary. The line holds the file, the line number, error:, the message and, at the end, a code in square brackets. Here the message is Argument 1 to "add_vat" has incompatible type "str"; expected "float", on line 5, with the code [arg-type], and the summary is Found 1 error in 1 file (checked 1 source file). mypy reported the call on line 5, which is where the mistake is, before the program ever ran. On the first example it reports four lines, one for each string and each list passed as an int. When it finds nothing, it says Success: no issues found in 1 source file. Some messages add a line starting note: under the error, with more detail.
mypy checks the inside of a function only when the function has hints. Without them, it says Success for a call that Python can't run:
def add(a, b):
return a + b
print(add(2, 3))
print(add(2, "3"))
# ✅ Expected output:
# 5
# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'int' and 'str'The messages quoted in this lesson come from mypy 1.19.1, and were the same when mypy checked for Python 3.11, 3.12, 3.13 and 3.14.
Hints for lists, dicts and tuples
For a container, the hint names what it holds, in square brackets: list[int] is a list of ints, dict[str, int] a dict from strings to ints, and tuple[float, float] a tuple of exactly two floats. Python keeps each one as written:
def report(scores: list[int], ages: dict[str, int], point: tuple[float, float]) -> None:
print(scores, ages, point)
report([90, 85], {"Ada": 36}, (1.5, 2.0))
print(report.__annotations__)
# ✅ Expected output:
# [90, 85] {'Ada': 36} (1.5, 2.0)
# {'scores': list[int], 'ages': dict[str, int], 'point': tuple[float, float], 'return': None}A variable can carry a hint too, after its name and before the =. Python doesn't look inside the container, so a string goes into a list of ints without complaint:
scores: list[int] = [90, 85]
scores.append("ninety")
print(scores)
# ✅ Expected output:
# [90, 85, 'ninety']mypy does: on the append() line it reports Argument 1 to "append" of "list" has incompatible type "str"; expected "int". And isinstance() can ask whether a value is a list, but cannot use list[int] to check the types of its contents:
scores = [90, 85]
print(isinstance(scores, list))
print(isinstance(scores, list[int]))
# ✅ Expected output:
# True
# ✅ Expected error:
# TypeError: isinstance() argument 2 cannot be a parameterized genericNone as a result, and values that may be None
A function that only does something, and returns nothing, is hinted -> None. Calling it still gives a value, None, as Functions showed:
def log(msg: str) -> None:
print("LOG:", msg)
result = log("saved")
print(result)
print(log.__annotations__)
# ✅ Expected output:
# LOG: saved
# None
# {'msg': <class 'str'>, 'return': None}Keeping that None in a variable is almost always a mistake, and mypy says so on the result = log("saved") line: "log" does not return a value (it only ever returns None), code [func-returns-value].
A function that sometimes has no answer returns None then, and its hint says so with float | None: a float, or None. The caller has to check which before using it:
def find_price(menu: dict[str, float], item: str) -> float | None:
return menu.get(item)
menu = {"tea": 1.5, "cake": 2.25}
for item in ["tea", "soup"]:
price = find_price(menu, item)
if price is None:
print(item, "is not on the menu")
else:
print(item, "costs", price * 2, "for two")
# ✅ Expected output:
# tea costs 3.0 for two
# soup is not on the menuAfter if price is None:, mypy knows that in the else branch the price is a float, so it finds no issues. Leave the check out and the program works until the first time there's no price:
def find_price(menu: dict[str, float], item: str) -> float | None:
return menu.get(item)
menu = {"tea": 1.5, "cake": 2.25}
print(find_price(menu, "tea") * 2)
print(find_price(menu, "soup") * 2)
# ✅ Expected output:
# 3.0
# ✅ Expected error:
# TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'mypy reports both lines, the one that worked as well: Unsupported operand types for * ("None" and "int"), code [operator], with the note Left operand is of type "float | None". It checks types, not values, and either call could have given None.
Older code writes Optional[str], from the typing module, for str | None. Both mean the same:
from typing import Optional
def old(name: str) -> Optional[str]:
return None
def new(name: str) -> str | None:
return None
print(old.__annotations__["return"] == new.__annotations__["return"])
# ✅ Expected output:
# TruePrinted, Optional[str] shows as typing.Optional[str] up to Python 3.13 and as str | None from 3.14. A parameter with a default of None needs | None in its hint too: for name: str = None, mypy reports Incompatible default for argument "name" (default has type "None", argument has type "str"), and name: str | None = None passes.
Python keeps the hints in __annotations__
Hints aren't comments: Python stores a function's hints in a dictionary, its __annotations__, with 'return' for the result:
def greet(name: str, times: int = 1) -> str:
return " ".join(["Hello " + name] * times)
print(greet("Ada", 2))
print(greet.__annotations__)
# ✅ Expected output:
# Hello Ada Hello Ada
# {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}In a class body, a name with a hint and no value is listed in the class's __annotations__, but it isn't an attribute. This is what Data Classes & Advanced Class Patterns builds on: @dataclass reads these hints and writes the methods that set them.
class User:
name: str
age: int = 0
print(User.__annotations__)
print(User.age)
print(User.name)
# ✅ Expected output:
# {'name': <class 'str'>, 'age': <class 'int'>}
# 0
# ✅ Expected error:
# AttributeError: type object 'User' has no attribute 'name'The same goes for a variable: a hint on its own gives the name no value, so the name doesn't exist.
total: int
print(total)
# ✅ Expected error:
# NameError: name 'total' is not definedWhen Python works out a hint, and naming a class inside itself
A hint is Python code, and Python works out its value at some point. Up to Python 3.13 that happens when the def runs. So a method of Basket that takes another basket, def merged(self, other: Basket) -> Basket:, stops the program with NameError: name 'Basket' is not defined as the class is being made: the name Basket only exists once the class body has finished. Python 3.14 works out hints only when something asks for them, so there the same class runs. mypy finds no issues on any version.
Two ways work on every version. Write the name in quotes, other: "Basket", or make from __future__ import annotations the file's first line, which keeps every hint in the file as text:
from __future__ import annotations
class Basket:
def __init__(self) -> None:
self.items: list[str] = []
def merged(self, other: Basket) -> Basket:
result = Basket()
result.items = self.items + other.items
return result
a = Basket()
a.items.append("tea")
b = Basket()
b.items.append("cake")
print(a.merged(b).items)
print(Basket.merged.__annotations__)
# ✅ Expected output:
# ['tea', 'cake']
# {'other': 'Basket', 'return': 'Basket'}typing.get_type_hints() turns hints kept as text back into the types they name:
from __future__ import annotations
import typing
def add(a: int, b: int) -> int:
return a + b
print(add.__annotations__)
print(typing.get_type_hints(add))
# ✅ Expected output:
# {'a': 'int', 'b': 'int', 'return': 'int'}
# {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}A hint on a variable inside a function is never worked out at all, so even a name that doesn't exist, as in count: Undefinedname = 1, runs without an error. If the function has hints, mypy reports it: Name "Undefinedname" is not defined.
If it runs, the types can still be wrong
A program that runs isn't proof that its types are right. Here label() gets a string where its hint says int, and the output looks fine:
def initials(name: str) -> str:
return name[0] + "."
def label(count: int) -> str:
return "items: " + str(count)
print(initials("Ada"))
print(label("3"))
# ✅ Expected output:
# A.
# items: 3mypy reports the call: Argument 1 to "label" has incompatible type "str"; expected "int". mypy also catches a function that is hinted to return a value and prints it instead:
def greet(name: str) -> str:
print("Hello " + name)
message = greet("Ada")
print(message.upper())
# ✅ Expected output:
# Hello Ada
# ✅ Expected error:
# AttributeError: 'NoneType' object has no attribute 'upper'Python only fails at the line that uses the result. mypy reports the function itself, on its def line: Missing return statement, code [return].
Functions as values: Callable, and a first look at Protocol
A function can be passed to another function, as Higher-Order Functions & Function Factories showed. Its hint is Callable, from collections.abc: Callable[[int, int], int] is a function that takes two ints and returns an int.
from collections.abc import Callable
def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
return fn(a, b)
def add(a: int, b: int) -> int:
return a + b
print(apply(add, 3, 4))
print(apply(max, 3, 4))
# ✅ Expected output:
# 7
# 4Pass a function that takes one number, and the call fails inside apply():
from collections.abc import Callable
def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
return fn(a, b)
def double(n: int) -> int:
return n * 2
print(apply(double, 3, 4))
# ✅ Expected error:
# TypeError: double() takes 1 positional argument but 2 were givenmypy reports the call instead: Argument 1 to "apply" has incompatible type "Callable[[int], int]"; expected "Callable[[int, int], int]".
Inheritance and Polymorphism added up the areas of things that only had to have an area() method. A Protocol writes that down for mypy: any object with a matching area() counts as a HasArea, whatever its class. At run time nothing changes, and a string in the list fails only when its turn comes:
from typing import Protocol
class HasArea(Protocol):
def area(self) -> float: ...
class Square:
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side * self.side
def total_area(things: list[HasArea]) -> float:
return sum(thing.area() for thing in things)
print(total_area([Square(2), "not a shape"]))
# ✅ Expected error:
# AttributeError: 'str' object has no attribute 'area'mypy reports the list before anything runs: List item 1 has incompatible type "str"; expected "HasArea", code [list-item]. Advanced Type Hints (Generics, Protocol, TypedDict) teaches Protocol properly.
Hints don't make code faster
Python stores the hints next to the function and runs the same code with or without them. The two functions below compile to the same bytecode, the instructions Python runs:
def plain(a, b):
return a + b
def typed(a: int, b: int) -> int:
return a + b
print(plain.__code__.co_code == typed.__code__.co_code)
# ✅ Expected output:
# TrueHints pay off before the program runs, in the mistakes mypy finds. To make code faster, measure it first, as Profiling & Optimising Python Performance does.
Practice: hint a small menu program
Fill in the three missing hints: the list of prices basket_total() takes, what find_price() returns when the item may be missing, and what show() returns, since it only prints. The 👉 comment at the end of each line gives the answer if you get stuck.
def basket_total(prices: ___) -> float: # 👉 replace ___ with list[float]
return round(sum(prices), 2)
def find_price(menu: dict[str, float], item: str) -> ___: # 👉 replace ___ with float | None
return menu.get(item)
def show(item: str, price: float | None) -> ___: # 👉 replace ___ with None
if price is None:
print(item, "is not on the menu")
else:
print(item, "costs", price)
menu = {"tea": 1.5, "cake": 2.25}
show("tea", find_price(menu, "tea"))
show("soup", find_price(menu, "soup"))
print(basket_total([1.5, 2.25, 2.25]))
print(basket_total.__annotations__)
print(find_price.__annotations__)
print(show.__annotations__)
# ✅ Expected output:
# tea costs 1.5
# soup is not on the menu
# 6.0
# {'prices': list[float], 'return': <class 'float'>}
# {'menu': dict[str, float], 'item': <class 'str'>, 'return': float | None}
# {'item': <class 'str'>, 'price': float | None, 'return': None}Run it with a blank still in and Python stops with NameError: name '___' is not defined: up to Python 3.13 at the first def, and on 3.14 at the first line that prints the hints, since that's when 3.14 works them out.
On your own: a port number that may be missing
Write parse_port(raw), where raw is a string or None, and the result an int or None. Return None when raw is None or isn't all decimal digits (raw.isdecimal() tells you), and int(raw) otherwise. Hint it with |, then print each of ["8080", None, "abc", "443", "²"] with "->" and its result, and finally parse_port.__annotations__.
# your code heredef parse_port(raw: str | None) -> int | None:
if raw is None:
return None
if not raw.isdecimal():
return None
return int(raw)
for raw in ["8080", None, "abc", "443", "²"]:
print(raw, "->", parse_port(raw))
print(parse_port.__annotations__)
# ✅ Expected output:
# 8080 -> 8080
# None -> None
# abc -> None
# 443 -> 443
# ² -> None
# {'raw': str | None, 'return': int | None}isdigit() also accepts characters such as ² that int() cannot parse. isdecimal() selects decimal digits. This exercise checks conversion; validating a port's allowed numeric range would be another check.
The hint int | None tells every caller to handle None. Add port = parse_port("8080") and print(port + 1), and Python prints 8081, but mypy reports Unsupported operand types for + ("None" and "int"), with the note Left operand is of type "int | None": for another string, the port would be None.
Practice quiz
def add(a: int, b: int) -> int returns a + b. What does print(add("2", "3")) print?
- 5
- It stops with TypeError
- 23
- It stops with ValueError
Answer: 23. Python doesn't check hints, and "2" + "3" joins two strings.
def double(n: int) -> int returns n * 2. What does print(double("21")) print?
- 42
- 2121
- It stops with TypeError
- 21
Answer: 2121. A hint doesn't convert the value either, so "21" * 2 repeats the string.
A program's first line is score: int, and its second is print(score). What happens?
- It prints 0
- It prints None
- It prints <class 'int'>
- It stops with NameError: name 'score' is not defined
Answer: It stops with NameError: name 'score' is not defined. An annotation on its own gives the name no value, so it doesn't create the variable.
A file starts with from __future__ import annotations and defines def area(w: float, h: float) -> float. What does print(area.__annotations__) print?
- {'w': 'float', 'h': 'float', 'return': 'float'}
- {'w': <class 'float'>, 'h': <class 'float'>, 'return': <class 'float'>}
- {}
- It stops with NameError: name 'float' is not defined
Answer: {'w': 'float', 'h': 'float', 'return': 'float'}. With that import, Python keeps every hint as the text you wrote. typing.get_type_hints() turns the text back into types.
What does print(isinstance([1, 2], list[int])) do?
- It prints True
- It prints False
- It stops with TypeError: isinstance() argument 2 cannot be a parameterized generic
- It prints [1, 2]
Answer: It stops with TypeError: isinstance() argument 2 cannot be a parameterized generic. isinstance() can check for a list, but it cannot use list[int] to check the types of the items inside it.
greet(name: str) -> str prints "Hello " + name and has no return. What does print(greet("Ada").upper()) do?
- It prints HELLO ADA
- It prints Hello Ada, then stops with AttributeError: 'NoneType' object has no attribute 'upper'
- It stops with TypeError before printing anything
- It prints Hello Ada, then None
Answer: It prints Hello Ada, then stops with AttributeError: 'NoneType' object has no attribute 'upper'. The function prints, then returns None, whatever its hint says. mypy would have reported Missing return statement.
find(menu, item) -> float | None returns menu.get(item). With menu = {"tea": 1.5}, the program runs price = find(menu, "tea") and print(price * 2). What happens when it runs, and what does mypy say?
- It prints 3.0, and mypy reports an error on the print line
- It prints 3.0, and mypy finds no issues
- It stops with TypeError, and mypy reports an error
- It stops with TypeError, and mypy finds no issues
Answer: It prints 3.0, and mypy reports an error on the print line. Tea is on the menu, so this run works. mypy checks types, not values: price might be None, and None * 2 fails.
def add(a, b) has no hints and returns a + b. What do mypy and Python say about print(add(2, "3"))?
- mypy reports an error, and Python prints 23
- mypy reports an error, and Python stops with TypeError
- mypy finds no issues, and Python prints 23
- mypy finds no issues, and Python stops with TypeError
Answer: mypy finds no issues, and Python stops with TypeError. mypy skips the inside of functions without hints, so it says Success. Python stops with TypeError: unsupported operand type(s) for +: 'int' and 'str'.
Continue this course
- Previous: Memory Management & Garbage Collection Internals
- Next: Data Classes & Advanced Class Patterns — Reduce boilerplate with @dataclass and slots
- Quick reference: Python cheat sheet › Functions
Frequently asked questions
How do I annotate *args?
Give the type of each extra argument: def total(*nums: int, sep: str = ", ") -> str means every number passed is an int. Its __annotations__ show 'nums': <class 'int'>, and mypy reports total(1, "2") as Argument 2 to "total" has incompatible type "str"; expected "int".
Do I have to annotate every variable?
No. mypy works out a variable's type from its first value: for scores = [90, 85], reveal_type(scores) makes mypy print Revealed type is "builtins.list[builtins.int]". It asks for a hint only when it can't tell, as with an empty list: names = [] gets Need type annotation for "names" (hint: "names: list[<type>] = ...").
Do I need List and Dict from typing?
Not since Python 3.9, which made list[int] and dict[str, int] work. typing.List and typing.Dict are the older spellings, and they still work.
What are type Point = ... and def first[T](...)?
Syntax that Python 3.12 added for type aliases and generic functions. On older versions, including the Python inside this site's Run button, it's a SyntaxError, and mypy itself has to run on 3.12 or newer to read it. Advanced Type Hints (Generics, Protocol, TypedDict) teaches it.
Can Python check values against the hints while the program runs?
Not by itself. Libraries can, and Data Validation with Pydantic teaches one of them.
What about Any, # type: ignore and --strict?
They tune mypy for a whole project: how strict it is, and what it skips. Static Type Checking with mypy covers them.
Is reveal_type a real function?
For mypy it's a request: mypy prints the type it worked out for the value, as a note. From Python 3.11 it's also in the typing module, and at run time it prints the value's type to stderr and returns the value unchanged. Take it out once you have your answer.