Skip to content
dreamcode
dreamcode
Map
Type hints
Lesson 48 of 77
+15 XP on finish
OBJECTSChapter 8 · Objects and Classes

Type hints

Type hints label what a variable or function expects: def area(w: float, h: float) -> float:. Python does not enforce them while running, but editors and checkers such as mypy read them to catch mistakes before you run, and they document your code for the next reader. list[str], dict[str, int] and str | None describe containers and optional values.

Worked example

How it reads

  • name: type after each parameter, -> type for the return value
  • int | None means the function might return nothing
  • Hints are notes for tools and people; the code runs the same without them
Cloud tip: Type hints pay off most on functions other people call. Start there.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Add type hints: name is a str, times is an int, and the function returns a str. Then print greet.__annotations__ to see them: {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}.

Press Run to check your work.