After this lesson you will be able to read the colons and arrows in function definitions that you will see in real-world Python code, and add them to your own functions so that other people, and your editor, understand what goes in and what comes out.
What a type hint looks like
A type hint is a label that says what type a value is expected to have. Parameters get a colon and a type, and the return value gets an arrow and a type.
def total_price(price: float, count: int) -> float:
return price * count
print(total_price(2.5, 4))10.0Variables can be annotated too:
shop_name: str = "Corner Books"
open_days: int = 6
prices: dict = {"pen": 2.5}
print(shop_name, open_days, prices)Corner Books 6 {'pen': 2.5}Read price: float as "price is meant to be a float". Read -> float as "this function returns a float".
Python does not enforce them
This surprises many beginners. Type hints are not rules that Python checks while the program runs. They are information. Pass a string where an int is hinted and Python carries on happily:
print(total_price("ab", 3))abababThe function ran and repeated the text three times, because multiplying a string by an integer is legal. The hint did not stop it. What hints do is let tools find mistakes before you run the program. A type checker such as mypy reads your hints and reports mismatches. Your editor also uses them to offer better auto-complete and warnings. Installing a checker is done from the command line:
pip install mypy
mypy shop.pyPython does keep the hints, so you can look at them:
print(total_price.__annotations__){'price': <class 'float'>, 'count': <class 'int'>, 'return': <class 'float'>}Collections
Hints for lists and dictionaries say what they contain. From Python 3.9 you can use the built-in names with square brackets:
def average(marks: list[int]) -> float:
return sum(marks) / len(marks)
def stock_value(stock: dict[str, int], price: float) -> float:
return sum(stock.values()) * price
print(average([72, 88, 91]))
print(stock_value({"pens": 40, "ink": 12}, 1.5))83.66666666666667
78.0Older code, and code that must run on Python 3.8 or earlier, uses names imported from the typing module instead: List[int], Dict[str, int], Tuple[int, str] and Set[str]. They mean the same thing.
from typing import Dict, List, Tuple
def first_and_last(names: List[str]) -> Tuple[str, str]:
return names[0], names[-1]
def count_words(words: List[str]) -> Dict[str, int]:
counts: Dict[str, int] = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
print(first_and_last(["Asha", "Ben", "Chloe"]))
print(count_words(["pen", "ink", "pen"]))('Asha', 'Chloe')
{'pen': 2, 'ink': 1}Optional and Union
Sometimes a value may be missing. Optional[int] means "an int or None". Union[int, str] means "either of those types".
from typing import Optional, Union
def find_price(prices: dict, item: str) -> Optional[float]:
return prices.get(item)
def label(value: Union[int, str]) -> str:
return "ID-" + str(value)
print(find_price({"pen": 2.5}, "pen"))
print(find_price({"pen": 2.5}, "ink"))
print(label(7), label("A9"))2.5
None
ID-7 ID-A9Newer versions of Python add a shorter way to write a union with a vertical bar between the types. Because this course targets Python 3.9, use Optional and Union.
A checker would notice if you use an Optional result without handling None, which is the most common mistake that hints help to catch:
def shout_price(prices: dict, item: str) -> str:
price = find_price(prices, item)
if price is None:
return "no price for " + item
return f"{item} costs {price:.2f}"
print(shout_price({"pen": 2.5}, "pen"))
print(shout_price({"pen": 2.5}, "ink"))pen costs 2.50
no price for inkOther useful hints
Any means any type at all. Callable describes a function that is passed around. A function that returns nothing is hinted -> None.
from typing import Any, Callable
def apply_twice(func: Callable[[int], int], value: int) -> int:
return func(func(value))
def log(message: Any) -> None:
print("LOG:", message)
print(apply_twice(lambda n: n + 5, 10))
log({"status": "ok"})20
LOG: {'status': 'ok'}Classes as types
Your own classes can be used as hints too, and so can the built-in types you have already met, such as str, bool and bytes.
class Book:
def __init__(self, title: str, pages: int) -> None:
self.title = title
self.pages = pages
def long_books(books: list[Book]) -> list[str]:
return [b.title for b in books if b.pages > 300]
print(long_books([Book("Dune", 612), Book("Emma", 250)]))['Dune']How much should you add?
You do not need to hint everything. Hints pay off most in function signatures, especially in functions used by other people or in larger programs. For a ten-line script, they add little. Start by annotating the parameters and return types of your functions, and let a checker tell you whether they agree with the code.
Common mistakes
- Believing hints are checked. Python ignores them at run time. Use a checker if you want them verified.
- Hinting
Nonereturns wrongly. A function that returns nothing should say-> None, not-> str. - Forgetting to handle
Optional. If a function can returnNone, the caller must check it before using the value. - Mixing styles. Choose either
List[int]fromtypingorlist[int], and stay consistent within a project. - Using
list[int]on very old Python. It works from Python 3.9. On older versions useList[int].
Exercise
Write a function discounted(price: float, percent: float) -> float that returns the price after a percentage discount, rounded to two decimals. Then write safe_discount(price: float, percent: Optional[float]) -> float that treats a missing percentage (None) as zero. Print discounted(80, 25), safe_discount(80, None) and safe_discount(80, 10).
Show one possible answer
from typing import Optional
def discounted(price: float, percent: float) -> float:
return round(price * (100 - percent) / 100, 2)
def safe_discount(price: float, percent: Optional[float]) -> float:
if percent is None:
percent = 0
return discounted(price, percent)
print(discounted(80, 25))
print(safe_discount(80, None))
print(safe_discount(80, 10))60.0
80.0
72.0Next: testing with unittest is the first lesson in the practice section. A video version of this topic is in the video course at /learn/python/.
Key points
- A type hint such as def total(price: float, count: int) -> float: describes what a function expects and returns.
- Python does not enforce hints when the program runs. They are documentation for people and for checkers such as mypy.
- Use Optional[X] for a value that may be None, Union[X, Y] for either type, and List[str], Dict[str, int] or list[str] for collections.
- Variables can be annotated too, for example name: str = 'Asha'.
- Hints are optional, so add them where they make code easier to understand.