Type Hints on Python Functions: Parameters, Returns, None and Collections
A type hint is a label on a jar: it says what belongs inside but stops nothing. Hint parameters and returns, -> None, str | None, list[str] and dict[str, int], see add("2", "3") print 23, and read hints back with __annotations__.
What you will learn
- Hint a function's parameters and return value, including -> None and defaults
- Use str | None for a value that might be missing, and check for None
- Hint what is inside a list or dict with list[str] and dict[str, int]
- Explain why Python does not enforce hints and who reads them instead
Before you start
- Python Functions: Parameters, Return, Scope, *args and **kwargs
- Python Lists, Tuples, Sets and Dicts
Until now, you had to read the body of a function to know what it expects. A type hint puts that on the very first line.
Think about a jar in your kitchen with a label that says sugar. Everybody knows what belongs inside without opening it. But the label doesn't guard anything. Pour salt in and the jar takes it, and you only find out later, when you taste your tea. That's a type hint: it tells everyone what should go in, but it doesn't stop anything.
You already know hints on variables, like name: str = "Alice", from lists, tuples, sets and dicts. A function asks the same question in two places: what goes in, and what comes out.
Parameter hints and return hints
def greet(name: str) -> str:
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
print(greet("Alice"))
print(add(2, 3))
Hello, Alice
5
name: str is a parameter hint: name should be a string. The arrow and str at the end is the return hint: greet gives back a string. add says two whole numbers go in and a whole number comes out.
A function that returns nothing
def log(message: str) -> None:
print("LOG:", message)
result = log("saved")
print(result)
LOG: saved
None
log only prints; there's no return, so the function hands back None. -> None tells the reader you call this function for what it does, not for what it gives back.
Hints with default values
def repeat(text: str, times: int = 2) -> str:
return text * times
print(repeat("ha"))
print(repeat("ha", 3))
haha
hahaha
The order is name, colon and type, then the default. With a hint, put spaces around the =.
A value or None
USERS = {1: "Alice", 2: "Bob"}
def find_user(user_id: int) -> str | None:
return USERS.get(user_id)
for uid in (1, 7):
user = find_user(uid)
if user is None:
print(uid, "-> not found")
else:
print(uid, "->", user)
1 -> Alice
7 -> not found
Sometimes a function can't promise a value. If the ID is in the dict you get a name; if not, get gives back None. So the return hint is str | None, where the bar means "or". The hint warns whoever calls the function to check for None before using the value. In older code you'll see Optional[str], which means the same thing.
What's inside a list or a dict
def shout_all(names: list[str]) -> list[str]:
return [n.upper() for n in names]
def total(scores: dict[str, int]) -> int:
return sum(scores.values())
print(shout_all(["ann", "bob"]))
print(total({"maths": 80, "art": 95}))
['ANN', 'BOB']
175
A hint that only says list leaves a question: a list of what? Put the type in square brackets. For a dict, name two types, keys first and then values: dict[str, int] means string keys and whole-number values. (The one-line list inside shout_all is a comprehension.)
Python doesn't check hints
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))
print(add("2", "3"))
5
23
Here's the part that surprises people. Passing two strings is exactly what the hints say not to do, and Python doesn't stop you. The plus sign is happy to join two strings, so it prints 23 and finishes without any error. Hints aren't enforced when your code runs, just like the label on that jar.
When a wrong type does fail
def add(a: int, b: int) -> int:
return a + b
print(add("2", 3))
Traceback (most recent call last):
File "S02L01_1_TypeHints\wrong_type_fails.py", line 5, in <module>
print(add("2", 3))
~~~^^^^^^^^
File "S02L01_1_TypeHints\wrong_type_fails.py", line 2, in add
return a + b
~~^~~
TypeError: can only concatenate str (not "int") to str
The values go straight past the hints and reach a + b. The error points at the plus sign on line 2 and says nothing about the hint. When a wrong type fails, it's the operation that fails.
Python keeps the hints
import inspect
def greet(name: str, times: int = 1) -> str:
return ("Hi " + name + " ") * times
print(greet.__annotations__)
print(inspect.signature(greet))
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}
(name: str, times: int = 1) -> str
Python doesn't check the hints, but it does keep them. __annotations__ is a dictionary, with the return hint under its own key, return. inspect.signature gives back the whole first line, default included. So other code can ask for the hints.
Who reads the hints
- Your editor. PyCharm reads the file without running it. On
add("2", "3")it marks the string and says it expected an int and got a str, before you run anything. And because it knowsnameis a string, typingname.offers you string methods. - AI tools. Hints tell them what each function takes and gives back. You can prompt one to add type hints, and then the first line of each function is the first thing to check.
- Libraries. Pydantic and FastAPI build on these same hints; see FastAPI hello world for where they show up.
Quick recap
| You write | It means |
|---|---|
name: str | this parameter should be a string |
-> int | the function returns an int |
-> None | called for what it does, returns nothing |
times: int = 2 | hint first, then default |
str | None | a string, or nothing; check before use |
list[str], dict[str, int] | what's inside the container |
And Python doesn't check any of it when your code runs.
Try it yourself
def average(numbers):
return sum(numbers) / len(numbers)
print(average([4, 8, 6]))
Add hints to average. It should still print 6.0.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
A function is a recipe: write it once, hand in ingredients, get a dish back. input and import, def and return, defaults, returning a tuple, functions as objects, the LEGB scope rule, global and nonlocal, then *args and **kwargs, with real output.
Python lambda, map, filter, Modules and Packages (with pip and venv)
A lambda is a sticky note next to a def recipe card. Sort words and students with key, map as a conveyor belt, filter as a gate, then your own package with __init__.py, two import errors, and pip install into an activated .venv.
Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
Three work-style use cases (an HR bonus calculator, a product discount pipeline, and a mathkit package) turned into requirement lists and prompts, with one possible result for each read against the list, including the empty-input crash the list forgot.
