Intermediate 8 min

Type hints and data contracts

Type hints describe the values a function expects and produces.

How it works

Hints help most at boundaries. list[int] tells a caller what each entry should be, while int | None says the result may be missing. When you offer that choice, a reader can see that they need to handle None before doing arithmetic.

Walk through an example

def double(n: int) -> int documents an integer input and integer output. An editor or static checker can use the hint to flag a call with text.

What to watch for

Python normally does not enforce annotations at runtime. Convert or validate outside input explicitly when the program needs that guarantee.

Code example

def double(n: int) -> int:
    return n * 2

print(double(7))

Check your understanding

What can this function return at runtime?

See the example and explanation
Worked example
Given def double(n: int) -> int: return n * 2; double("a")
Answer "aa"

The annotation is descriptive. Python applies string repetition when a string is multiplied by 2.

Open practice problem
Next lessonVirtual environments and dependencies