Type hints
Type hints state what types a function expects and returns. Python itself ignores them at runtime, but editors, linters and type checkers such as mypy use them to catch mistakes before you run the code, and they make functions self-documenting.
Annotating a function
Python
def greet(name: str, times: int = 1) -> str:
return ("Hello, " + name + "! ") * times
print(greet("Asha", 2))name: strsaysnameshould be a string,-> strsays the function returns a string.
Hints don't enforce anything
Python
def double(n: int) -> int:
return n * 2
print(double(4))
print(double("ha")) # Python runs it anywayA type checker would flag double("ha"); Python doesn't. Hints are documentation that tools can verify.
Collections
Since Python 3.9, the built-in collection types take the item type in square brackets:
Python
def average(scores: list[float]) -> float:
return sum(scores) / len(scores)
def count_words(text: str) -> dict[str, int]:
counts: dict[str, int] = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return counts
print(average([72.5, 88.0, 91.5]))
print(count_words("to be or not to be"))| Hint | Means |
|---|---|
list[int] | a list of ints |
dict[str, float] | keys are strings, values floats |
tuple[int, int] | exactly two ints |
set[str] | a set of strings |
Optional values and unions
When a value can be one of several types, use | (Python 3.10+). X | None means "an X, or None":
Python
def find_user(user_id: int) -> str | None:
users = {1: "Asha", 2: "Leo"}
return users.get(user_id)
def to_number(value: int | str) -> int:
return int(value)
print(find_user(1), find_user(9))
print(to_number("42") + to_number(8))Older code writes these as Optional[str] and Union[int, str] from the typing module; they mean the same thing.
Hints in classes
Hints are what dataclasses use to discover their fields:
Python
from dataclasses import dataclass
@dataclass
class Order:
order_id: int
items: list[str]
paid: bool = False
o = Order(101, ["Keyboard", "Mouse"])
print(o)
print(Order.__annotations__)Reading hints at runtime
Python
def area(width: float, height: float) -> float:
return width * height
print(area.__annotations__)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.