LevelJar Sign in

Python course / Working Python

Type hints

Say what your functions take and hand back, and read what a type checker tells you. Python stores hints and never checks them, which is the first thing most people get wrong about them.

  • function hints
  • collections
  • X | None
  • unions
  • Any
  • Protocols
  • TypedDict
  • type checkers

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

hints are stored, not enforced
def total(prices: list[float], discount: float | None = None) -> float:
    amount = sum(prices)
    if discount is not None:
        amount -= discount
    return amount


print(total([3.5, 2.25]))
print(total([3.5, 2.25], discount=1.0))
print("hints:", total.__annotations__)
5.75
4.75
hints: {'prices': list[float], 'discount': float | None, 'return': <class 'float'>}

What you will learn

The lessons in this module

  • What a hint is, and what it is not
  • Hinting a function
  • Reading hints back
  • Hinting variables and attributes
  • Hinting collections
  • Maybe nothing: X | None
  • Unions, and when they keep growing
  • Any
  • Hinting your own classes
  • Hinting functions: Callable
  • Protocols: hinting what an object can do
  • TypedDict: hinting a dictionary's shape
  • Type checkers
  • When hints earn their place
  • Hinting a module, and what it finds
  • Module review: the price list

Ready when you are

Start this module

Previous: Comprehensions. Next: Standard library tour. All modules are on the course page.