Type hints
A type hint is an annotation such as tokens: int that says what type a value should be, for people, editors and tools to read.
Last updated: 30 Sep, 2026 · Python 3.14
The dataclass in dataclasses had id: int in it. The same annotations work on functions, and they are how frameworks learn what your code expects.
Syntax:
def name(param: type, other: type = default) -> return_type:
...Adding hints to cost
def cost(tokens: int, price_per_1000: float = 0.15) -> float:
return round(tokens / 1000 * price_per_1000, 4)
print(cost(1200))0.18
tokens: int says tokens should be an int. -> float says what the function returns. The code runs as it did in Function arguments; the hints are for people, editors, and tools that read them.
Passing the wrong type anyway
print(cost("1200"))Traceback (most recent call last):
File "main.py", line 1, in <module>
print(cost("1200"))
TypeError: unsupported operand type(s) for /: 'str' and 'int'Python ran the function with a string, and it failed on the division inside, not at the call; on your computer the traceback also shows that line inside cost. An editor with type checking would underline cost("1200") before you run anything, which is the practical reason to write hints.
Hinting lists, dictionaries and None
def find_customer(tickets: list[dict], ticket_id: int) -> str | None:
for ticket in tickets:
if ticket["id"] == ticket_id:
return ticket["customer"]
return None
tickets = [{"id": 1, "customer": "Asha"}, {"id": 2, "customer": "Ben"}]
print(find_customer(tickets, 2))
print(find_customer(tickets, 9))Ben None
list[dict] is a list of dictionaries. str | None means a string or nothing, and warns whoever calls it to handle the None.
Reading the hints from code
print(cost.__annotations__){'tokens': <class 'int'>, 'price_per_1000': <class 'float'>, 'return': <class 'float'>}Hints are stored on the function, and any code can read them. A framework reads them the same way when it turns your function into a tool description for a model.
Type hints vs checks
| Type hint | A check | |
|---|---|---|
| Written as | tokens: int | if not isinstance(tokens, int): raise ... |
| When a wrong value arrives | Nothing happens | The program stops with an error |
| Read by | People, editors, frameworks | Python, every run |
Where type hints show up in AI code
- Tool functions: the hints become the argument types a model is told about.
- Pydantic models, where the same hints turn into real checks.
- Every modern library's own code, so your editor can suggest the right arguments.
cost("1200") is still a string inside the function; nothing turns it into 1200.Related
- Previous: Inheritance
- Next: Pydantic models
- Reference: typing in the Python docs
- Add hints to
categorisefrom Functions. - Print
find_customer.__annotations__. - Change
-> str | Noneto-> strand run it. Does anything change?
This is what real progress feels like.