Mental model: A type hint is a label. Like the label on a shelf, it tells you what belongs there without you having to look. Hints on a function's
def line say what kind of values go in and what kind comes back, so you don't have to read the whole function to find out. They describe the kind of value, not the value itself.Why it matters: In real programs like inventory trackers or sensor dashboards, you often pass data between many functions. Without hints, passing the wrong kind of value (text where a number belongs) might slide through until the app crashes at 3 AM. Hints let your editor flag that mismatch while you are still writing.
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))a and b should be ints; the result is an int.The syntax is straightforward. After each parameter name, place a colon and its type. After the closing bracket, use an arrow (
These hints are documentation. Python doesn't check them when your code runs. If you call
->) to declare the return type.These hints are documentation. Python doesn't check them when your code runs. If you call
add('two', 'three'), it will still run and return 'twothree', but your editor can warn you before you hit Enter.Modern collection syntax
def first_even(nums: list[int]) -> int | None:
for n in nums:
if n % 2 == 0:
return n
return None
print(first_even([3, 7, 8])) # 8
print(first_even([1, 5, 9])) # Nonelist[int] means a list of whole numbers. int | None means a whole number, or None.Since Python 3.9, square brackets after
list or dict say what's inside:list[str]: a list of text.dict[str, int]: a dictionary with text keys and whole-number values.dict[str, object]: text keys, and values of any kind (objectmeans any kind of value).set[float]andtuple[int, ...](a tuple of whole numbers, any length) work the same way.
str | None reads as text or None. The bar needs Python 3.10 or newer.def lookup(name: str) -> dict[str, list[int]]:
data = {'alice': [10, 20], 'bob': [30]}
return {name: data.get(name, [])}
print(lookup('alice')) # {'alice': [10, 20]}dict[str, list[int]]: a dictionary with text keys, and lists of whole numbers as values.