Python Type Hints
A type hint is a small label that says what type a value should be.
Annotate a variable
A colon and a type follow the name. The value still comes after an equals sign.
name: str = "Ada"
age: int = 36
print(name, age)Hint a parameter and a return
The parameter gets a hint after its name. The return hint follows an arrow.
def double(n: int) -> int:
return n * 2
print(double(21))Hint text in and out
Both hints here use str. The function takes text and returns text.
def greet(name: str) -> str:
return f"Hello, {name}!"
print(greet("Ada"))Say there is no return value
Some functions print and return nothing. Write None as the return hint.
def announce(text: str) -> None:
print(text)
announce("Ready")Hints do not block a call
Python runs this call anyway. Doubling text just repeats it, so no error appears.
def double(n: int) -> int:
return n * 2
print(double("ha"))Example
def greet(name: str) -> str:
return f"Hello, {name}!"
def min_max(numbers: list) -> tuple:
return min(numbers), max(numbers)
scores: list = [72, 95, 61, 88]
low, high = min_max(scores)
print(greet("Ada"))
print("Low:", low)
print("High:", high)Key points
- Annotation: a type hint attached to a variable, a parameter, or a return value
- Use name: type to annotate a variable, like age: int = 36
- Use -> type after the brackets to annotate what a function returns
- Use -> None for a function that returns no value
- Gradual typing: add hints a little at a time, only where they help most
In this example, greet takes a name as text. It returns a greeting as text. Next, min_max takes a list of whole numbers. Its hint names the container only: list. The next lesson adds the item type inside, like list[int]. The return hint is tuple, with no item types yet. The scores list holds whole numbers. The call stores the smallest and largest values. The prints show the greeting and both values. Nothing about the run changes.
Note
Python does not enforce hints at run time, so a separate checker must read them.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does the hint -> None say about a function?