Type hints

Functions, lesson 8 of 8

🧩 Functions, lesson 8 of 8

Type hints

Label what goes into and out of a function, and see that Python doesn't check the labels.

8 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A type hint labels a value with the type you expect it to have. Put name: type on a parameter, and -> type after the parentheses for the return value.

Hints are for people and tools to read. Python stores them, but it doesn't check them when your code runs.

Example

Hints on a function

Delete the hints and the output stays the same.

The common types are int, float, str and bool. For collections, say what the items are:

  • list[int]: a list of ints
  • dict[str, int]: a dict with string keys and int values
  • X | None: a value of type X, or None, for example "not found".
Example

Collections and optional results

scores.get(name) returns None when the name is missing, which is exactly what int | None promises.

Example

Hints are labels, not checks

The string "ab" goes through the same code without a complaint. Python doesn't check the hint (a type checker such as mypy would flag it before you run the code).

Quiz

What does this print?

Quiz

Which hint means a list where every item is an int?

Exercise

Describe a person

Add type hints to describe and make age optional.

describe("Ana", 30) returns "Ana (age 30)". When the age is left out, describe("Ben") returns "Ben (age unknown)".

Add these hints:

  • name is a str
  • age is int | None
  • the function returns a str