Code

Label the Crates

A type hint (or annotation) is a label saying what type a value should be. Parameters get : type, and the return value gets -> type:

def greet(name: str, times: int = 1) -> str:
    return ("Hi " + name + "! ") * times

lanterns: int = 12        # variables can be annotated too

Why bother?

  • Readers instantly know what to pass and what comes back.
  • Editors autocomplete better and warn about mistakes as you type.
  • Type checkers like mypy or pyright scan a whole project and catch bugs (like passing a str where an int belongs) before the code even runs.

Python stores the hints on the function, so tools can read them:

from typing import get_type_hints
print(get_type_hints(greet))
# {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}

Pip tip: A function that returns nothing is annotated -> None.

Assignment

The two functions already work. Add type hints:

  1. fuel_cost: liters and price_per_liter are float, and it returns a float.
  2. lantern_label: name is a str, count is an int (keep the default 1), and it returns a str.