Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 67 of 70

Python type hints for beginners

Add type hints to variables, parameters and return values, use Optional, Union and generic types from typing, and learn why Python does not enforce them.

12 minGoing furtherUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonAnnotate functions and variables with type hints, use Optional, List, Dict and Union, and explain that hints are checked by tools rather than by Python itself.

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.

python
def total_price(price: float, count: int) -> float:
    return price * count

print(total_price(2.5, 4))
result
10.0

Variables can be annotated too:

python
shop_name: str = "Corner Books"
open_days: int = 6
prices: dict = {"pen": 2.5}

print(shop_name, open_days, prices)
result
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:

python
print(total_price("ab", 3))
result
ababab

The 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:

bash
pip install mypy
mypy shop.py

Python does keep the hints, so you can look at them:

python
print(total_price.__annotations__)
result
{'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:

python
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))
result
83.66666666666667
78.0

Older 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.

python
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"]))
result
('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".

python
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"))
result
2.5
None
ID-7 ID-A9

Newer 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:

python
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"))
result
pen costs 2.50
no price for ink

Other useful hints

Any means any type at all. Callable describes a function that is passed around. A function that returns nothing is hinted -> None.

python
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"})
result
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.

python
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)]))
result
['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 None returns wrongly. A function that returns nothing should say -> None, not -> str.
  • Forgetting to handle Optional. If a function can return None, the caller must check it before using the value.
  • Mixing styles. Choose either List[int] from typing or list[int], and stay consistent within a project.
  • Using list[int] on very old Python. It works from Python 3.9. On older versions use List[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
python
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))
result
60.0
80.0
72.0

Next: 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.

Check yourself

1. What happens at run time if you pass a string to a parameter hinted as int?
2. What does Optional[int] mean?
3. Where does the return type go in a function definition?
4. Which annotation describes a dictionary with string keys and integer values?