Intermediate Python · Lesson 13 of 14
Type hints
Add type hints to variables, functions and classes, describe lists, dictionaries and optional values, and let a checker find bugs before you run code.
Type hints are notes in your code that say what kind of value a variable, parameter or return value should hold. After a parameter name write a colon and the type; after the brackets of a def write -> and the return type.
def price_with_tax(price: float, rate: float = 0.2) -> float:
return round(price * (1 + rate), 2)
city: str = "Accra"
visitors: int = 1200
print(price_with_tax(50.0), city, visitors)60.0 Accra 1200
Python itself does not check hints when the code runs. They are for people reading the code, for your editor (better suggestions and warnings) and for checking tools. Wrong types still run, or fail later in a confusing way.
def double(n: int) -> int:
return n * 2
print(double(4))
print(double("ha"))8 haha
The hint says int, but Python happily doubles a string.
Hints for collections
Put the type of the items in square brackets: list[str] is a list of strings, dict[str, float] maps strings to floats, tuple[int, int] is a pair of whole numbers. X | None means "an X or nothing", which suits functions that may not find a result.
def average(scores: list[float]) -> float:
return sum(scores) / len(scores)
def find_price(prices: dict[str, float], item: str) -> float | None:
return prices.get(item)
def min_max(values: list[int]) -> tuple[int, int]:
return min(values), max(values)
menu = {"soup": 5.5, "salad": 7.0}
print(average([6.5, 8.0, 9.5]))
print(find_price(menu, "soup"), find_price(menu, "cake"))
print(min_max([4, 9, 1]))8.0 5.5 None (1, 9)
Type aliases, callables and classes
Give a long type a short name by assigning it, like any value. Callable[[float], float] from collections.abc describes a function that takes a float and returns a float. Your own classes are types too.
from collections.abc import Callable
from dataclasses import dataclass
Prices = dict[str, float]
@dataclass
class Order:
customer: str
items: list[str]
def apply_to_all(prices: Prices, rule: Callable[[float], float]) -> Prices:
return {name: rule(p) for name, p in prices.items()}
def first_items(orders: list[Order]) -> list[str]:
return [o.items[0] for o in orders if o.items]
print(apply_to_all({"tea": 3.0, "cake": 4.0}, lambda p: p + 1))
print(first_items([Order("Ana", ["tea", "cake"]), Order("Bo", [])])){'tea': 4.0, 'cake': 5.0}
['tea']Checking hints with a tool
A type checker such as mypy reads your files without running them and reports calls that do not match the hints. On your own computer you install it with pip install mypy and run mypy your_file.py. Many editors run a checker as you type.
def total(prices: list[float]) -> float:
return sum(prices)
prices = ["4.50", "3.20"] # strings, not numbers
total(prices)
# mypy reports: Argument 1 to "total" has incompatible type "list[str]"; expected "list[float]"The checker finds this bug before the program ever runs.
isinstance() and raise an error. Hints alone never stop anything.✎ Exercise
Write total_price(items: dict[str, float], discount: float = 0.0) -> float that adds up the prices, takes off the discount (0.1 means 10%) and rounds to 2 places. Add the hints exactly as shown.
Hint: sum(items.values()) adds the prices; multiply by (1 - discount) and round.
# your code here
basket = {"bread": 2.4, "olive oil": 8.9, "tomatoes": 3.15}
print(total_price(basket))
print(total_price(basket, discount=0.1))
Expected output:
14.45 13.0
Show a solution
def total_price(items: dict[str, float], discount: float = 0.0) -> float:
return round(sum(items.values()) * (1 - discount), 2)
basket = {"bread": 2.4, "olive oil": 8.9, "tomatoes": 3.15}
print(total_price(basket))
print(total_price(basket, discount=0.1))14.45 13.0
Check yourself
1. What happens when you call def f(n: int) with a string?
Hints are notes for people and tools; Python does not enforce them.
2. Which hint means "a dictionary from names to prices"?
dict[key type, value type].
3. What does -> str | None say about a function?
The part after -> describes the return value.