Paul's Python CoursePPC

Type hints

Not met yet

A type hint is a note about what a value should be: stamps: int for a parameter, -> int for what a function returns, list[Postcard] for a list of postcards. Python doesn't check or convert anything when it runs; editors and checkers like mypy read the hints and warn you. Dataclasses use hints to find their fields.

Try it

main.py
def postage(stamps: int, price: int) -> int:
    return stamps * price

print(postage(3, 85))
print(postage("3", 2))

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks Python checks type hints when the program runs and stops on a mismatch.
  • Thinks a type hint converts the value to that type.
  • Thinks a type hint like count int gives the field or parameter a default value.

Where it comes up