Type Hints for Functions

Type hints document the kinds of values a function expects and returns.

Read it aloud:

mean takes a list of floats and returns a float

Parameter hints

The hint after a parameter name describes the expected type:

values: list[float]

This means values should be a list whose items are floats.

Return hints

The arrow describes the return type:

-> float

This means the function should return a float.

Type hints document a function

Runs locally with Python in your browser.

Ready to run.

__annotations__ shows the hints stored on the function. These hints do not make Python check every call by default.

Hints are not conversions

This hint:

does not convert "3" into 3. It tells the reader what the function expects.

If text must become a number, convert explicitly:

number = int(text)

Use simple hints first

These are enough for this subject:

HintMeaning
intinteger
floatfloating-point number
strtext
booltrue or false
list[float]list of floats
dict[str, int]dictionary from strings to integers
Exercise: Read the return hint

In this function header, what type is the function expected to return?

def count_words(text: str) -> int:

Answer it first, then check.

HintRead after the arrow

Parameter hints appear inside the parentheses; the return hint follows ->.

SolutionThe return hint is int

The header ends with -> int, so the function is expected to return an integer.