Academic Block

Python Type Hints and AnnotationsGet Certified

What Are Type Hints?

Python is a dynamically typed language, so a variable can hold a string now and a number a moment later, and Python never complains in advance. This freedom is convenient in small scripts, but in a larger program it becomes hard to remember whether a function expects a name, a list of names, or a number. A type hint, also called a type annotation, is a small label in the code that says what kind of value a variable, a parameter, or a return value is supposed to hold. The hints document your intentions for other people, and editors and type checkers use them to catch mistakes before the program runs.

  • Variable annotations: write a colon and a type after the name, as in age: int = 25.
  • Function annotations: describe each parameter and use -> for the return type.
  • Collection types: list[str], dict[str, int], and tuple[str, int] describe what is inside a container.
  • Optional and union types: str | None and int | str allow more than one kind of value.
  • The typing module: Literal, Callable, TypeVar, and more advanced helpers.
  • Hints are optional: Python does not enforce them while the program runs.

Annotating Variables and Functions

The basic syntax is simple: after a variable name or a parameter name you write a colon and the type, and after the closing parenthesis of a function you write an arrow -> and the type that the function returns. The common built-in types are int, float, str, bool, and None. A function that returns nothing is annotated with -> None. Python stores the annotations of a function in its __annotations__ attribute, which proves that they are kept as plain information and do not change how the code runs.

Try It: Annotating a City Report

Click Test My Code. Change the city to "Denver" and the population to a new number, then run it again.

What this code does: It annotates four variables with str, int, float, and bool. It then defines a function with annotated parameters and a return type, calls it, and prints the annotations that Python stored for that function.
city: str = "Austin"
population: int = 979_882
average_temp: float = 69.5
is_capital: bool = True

def describe_city(name: str, people: int) -> str:
    return f"{name} has {people:,} people"

print(describe_city(city, population))
print(describe_city.__annotations__)
print(type(average_temp).__name__, type(is_capital).__name__)

Type Hints Are Not Enforced at Runtime

This is the most important fact about type hints: Python itself does not check them while the program runs. If a function says that it wants a float and you pass a string, Python still tries to run the code, and the result depends on what the code does with that value. The real checking is done by outside tools such as mypy, Pyright, and the code editors that you use every day, and these tools read your hints and warn you about mismatches before you run anything. So the hints are a safety net for the programmer, and not a locked door for the interpreter.

Try It: A Hint That Python Ignores

Click Test My Code. Notice that the wrong call at the end does not crash, and think about which result a type checker would have warned you about.

What this code does: It defines a function that adds sales tax and is annotated with floats. A correct call prints a price. A second call passes a string and an integer, which breaks the hints, but Python runs it anyway and produces a surprising result.
def add_tax(price: float, rate: float) -> float:
    return price * (1 + rate)

total = add_tax(20.0, 0.0825)
print(f"Total: ${total:.2f}")

result = add_tax("ab", 2)
print(result)
print(type(result).__name__)

Hinting Lists, Dictionaries, and Tuples

Real programs work with containers, and a hint such as plain list does not say what is inside. In modern Python you put the type of the items in square brackets: list[int] is a list of integers, dict[str, int] is a dictionary with string keys and integer values, and set[str] is a set of strings. A tuple is special because its length and each position can have their own type, so tuple[str, int] means exactly two items, a string and then an integer. These precise hints make functions much easier to read and to use correctly.

  • list[int] is a list in which every item is an integer.
  • dict[str, float] maps string keys to float values.
  • set[str] is a set of strings.
  • tuple[str, int] is a tuple with exactly two items, in that order.
  • tuple[int, ...] is a tuple of any length that holds only integers.

Try It: A Roster and Score Keeper

Click Test My Code. Add a new name to the players list and a new score to the call, then run it again.

What this code does: It defines three functions with container hints: one that averages a list of integers, one that builds a dictionary from a list of names, and one that returns a tuple with a city and its population. It calls all three and prints the results.
def average_score(scores: list[int]) -> float:
    return sum(scores) / len(scores)

def make_roster(names: list[str]) -> dict[str, int]:
    return {name: len(name) for name in names}

def best_city() -> tuple[str, int]:
    return ("Chicago", 2746388)

players: list[str] = ["Jake", "Sophia", "Mason"]
print(average_score([88, 92, 79, 95]))
print(make_roster(players))
city, people = best_city()
print(city, people)

Optional Values and Union Types

Sometimes a value can be one of several types, or it can be missing altogether. A function that looks something up, for example, returns the answer when it exists and None when it does not. You describe this with the union operator |: str | None means “a string or nothing”, and int | str means “an integer or a string”. Older code uses Optional[str] and Union[int, str] from the typing module, which mean the same thing. When a hint includes None, the code that receives the value should check for None before it uses the value.

Try It: Phone Book and ZIP Codes

Click Test My Code. Look up "Noah" instead of "Ava" in the last block and run it again.

What this code does: It defines a lookup function that returns a phone number or None, and a formatting function that accepts a ZIP code as an integer or a string. It prints several lookups and then checks for None before it reports a missing contact.
def find_phone(contacts: dict[str, str], name: str) -> str | None:
    return contacts.get(name)

def format_zip(code: int | str) -> str:
    return str(code).zfill(5)

contacts: dict[str, str] = {"Emma": "555-0142", "Noah": "555-0178"}
print(find_phone(contacts, "Emma"))
print(find_phone(contacts, "Ava"))
print(format_zip(2108))
print(format_zip("90210"))

phone = find_phone(contacts, "Ava")
if phone is None:
    print("No phone number on file")

Type Aliases and Literal Values

As hints grow more complex, they become long and repetitive, and a type alias gives a complicated type a short and meaningful name. You create one with a simple assignment such as Coordinates = tuple[float, float], and from then on you can use Coordinates in your hints. The Literal type from the typing module goes in the other direction and limits a value to a few exact choices, such as "small", "medium", and "large". Both tools make the code read almost like plain English, and a type checker can warn you if you use a value that is not allowed.

Try It: Coffee Sizes and Map Points

Click Test My Code. Change the size to "large" and add a third city to see how the alias is reused.

What this code does: It creates an alias for a pair of coordinates and a Literal type for three coffee sizes. One function looks up a price for a size, another function describes a trip between two coordinate pairs, and the program prints both results.
from typing import Literal

Coordinates = tuple[float, float]
Size = Literal["small", "medium", "large"]

def coffee_price(size: Size) -> float:
    prices = {"small": 2.95, "medium": 3.45, "large": 3.95}
    return prices[size]

def distance_label(start: Coordinates, end: Coordinates) -> str:
    return f"From {start} to {end}"

seattle: Coordinates = (47.61, -122.33)
portland: Coordinates = (45.52, -122.68)
print(coffee_price("medium"))
print(distance_label(seattle, portland))

Type Hints in Classes and Dataclasses

Type hints are very useful for describing the data that an object holds. In a class, you can annotate the attributes and the methods, so that anyone who reads the class can see at a glance what each part is for. The @dataclass decorator from the dataclasses module goes one step further: it reads the annotations of the class body and builds the __init__(), __repr__(), and comparison methods for you. This is one of the few places where Python really uses the annotations at runtime, because the dataclass needs the names and the order of the annotated fields.

Try It: A Student Record

Click Test My Code. Create a third student with a GPA of 3.5 and check whether the student makes the honor roll.

What this code does: It defines a Student dataclass with three annotated fields, one of them with a default value, and a method that returns a Boolean. It creates two students, prints one of them, tests the honor roll for both, and prints the stored field annotations.
from dataclasses import dataclass

@dataclass
class Student:
    name: str
    grade: int
    gpa: float = 3.0

    def honor_roll(self) -> bool:
        return self.gpa >= 3.5

emma = Student("Emma Davis", 11, 3.8)
jake = Student("Jake Miller", 10)
print(emma)
print(emma.honor_roll(), jake.honor_roll())
print(Student.__annotations__)

Generics and Callable Types

Some functions work with many different kinds of values, and for them the hint should say “whatever type goes in comes out”. A type variable created with TypeVar does exactly that: if you pass in a list of strings, the result is a string, and if you pass in a tuple of integers, the result is an integer. Functions are values as well, and the Callable hint describes them: Callable[[float], float] means a function that takes one float and returns a float. The abstract type Iterable accepts lists, tuples, sets, and anything else that a for loop can walk through.

  • TypeVar("T") creates a placeholder that stands for any single type.
  • Iterable[T] accepts any object that can be looped over, with items of type T.
  • Callable[[int, int], str] is a function with two integer parameters that returns a string.
  • Any turns off type checking for one value, so use it rarely.

Try It: First Item and Discounts

Click Test My Code. Change the lambda to lambda p: p - 10 and run it again.

What this code does: It defines a generic function that returns the first item of any iterable, or a default value when the iterable is empty. It also defines a function that receives another function as a parameter. The program calls them with lists, an empty list, a tuple, and a lambda.
from typing import Callable, Iterable, TypeVar

T = TypeVar("T")

def first_item(items: Iterable[T], default: T) -> T:
    for item in items:
        return item
    return default

def apply_discount(price: float, rule: Callable[[float], float]) -> float:
    return rule(price)

print(first_item(["Boston", "Denver"], "none"))
print(first_item([], "no cities"))
print(first_item((10, 20, 30), 0))
print(apply_discount(80.0, lambda p: p * 0.75))

Reading Type Hints at Runtime

Although Python does not enforce hints, they are stored as ordinary data that your own code can read. The typing.get_type_hints() function returns a dictionary that maps each parameter name to its type, and the __annotations__ attribute holds the raw version. Libraries use this feature for useful jobs such as validating the data of a web request, generating documentation, and building command-line tools from function signatures. You can also write a tiny checker yourself, as in the next example, to see how the idea works.

Try It: A Tiny Type Checker

Click Test My Code. Change age="twenty" to age=20 and see all the checks pass.

What this code does: It defines a registration function with hints and a helper that reads those hints with get_type_hints(). The helper compares the type of each value that you give it with the expected type and prints whether the value is correct.
from typing import get_type_hints

def register(name: str, age: int, state: str = "TX") -> str:
    return f"{name}, {age}, {state}"

def check_types(func, **values):
    hints = get_type_hints(func)
    for key, value in values.items():
        expected = hints[key]
        status = "OK" if isinstance(value, expected) else "WRONG"
        print(f"{key}: {status} ({type(value).__name__} vs {expected.__name__})")

check_types(register, name="Olivia", age="twenty", state="TX")
Tip: Add hints to the signatures of your functions first, because that is where they help the most. Use simple built-in types such as list[str] and dict[str, int] before you reach for typing helpers, and install a checker such as mypy or Pyright in your editor to see mistakes while you type.

Using Type Hints with User Input

The input() function always returns a string, so type hints are a natural way to show where text becomes a number. When you write miles: float = float(input(...)), the hint tells the reader what the variable holds after the conversion. Hints also make the helper functions in an interactive program clear, because each one states what it receives and what it gives back. Remember that a hint does not convert anything by itself, so you still have to call int() or float() on the text that the user types.

Try It: A Road Trip Fuel Check

The Program Input box is already filled with two lines: 420 and 12. Click Run Code straight away, then try 260 and 13.

What this code does: It asks for the miles driven and the gallons of gas used, and converts both answers to floats. A typed function calculates miles per gallon, and a second typed function turns the result into a rating. The program prints the efficiency and the rating.
def miles_per_gallon(miles: float, gallons: float) -> float:
    return miles / gallons

def rate(mpg: float) -> str:
    return "Great" if mpg >= 30 else "Average" if mpg >= 20 else "Low"

miles: float = float(input("Miles driven: "))
gallons: float = float(input("Gallons used: "))
mpg: float = miles_per_gallon(miles, gallons)
print(f"{mpg:.1f} MPG - {rate(mpg)}")

Try It: A Diner Order Total

The Program Input box is filled with burger, 3. Click Run Code, then try taco, 2 and watch the None case.

What this code does: It asks for an item and a quantity in one line, such as burger, 3. A typed function splits the text into a string and an integer, and another function looks up the price. It returns None for an item that is not on the menu, and the program handles both cases.
def parse_order(text: str) -> tuple[str, int]:
    item, quantity = text.split(",")
    return item.strip(), int(quantity)

def total_cost(prices: dict[str, float], item: str, quantity: int) -> float | None:
    if item not in prices:
        return None
    return prices[item] * quantity

menu: dict[str, float] = {"burger": 8.99, "fries": 3.49, "shake": 5.25}
order: str = input("Order (item, quantity): ")
name, count = parse_order(order)
cost = total_cost(menu, name, count)
if cost is None:
    print(f"Sorry, {name} is not on the menu")
else:
    print(f"{count} x {name} = ${cost:,.2f}")

Common Mistakes with Type Hints

Type hints are easy to write, but a few misunderstandings cause confusion for new students and even for experienced programmers. Most of them come from expecting Python to enforce the hints, or from writing a hint that is less precise than it looks. The list below covers the problems that appear most often, and it is worth a quick read whenever an editor shows a warning that you do not understand, or whenever a program runs with the wrong type of value without any error.

  • Expecting Python to enforce hints: the interpreter ignores them at runtime. Use a checker such as mypy or Pyright, or validate the values yourself.
  • Using a bare list or dict: it does not say what is inside. Write list[str] or dict[str, int].
  • Forgetting None in the return type: a function that sometimes returns nothing needs -> str | None, and the caller must check for None.
  • Overusing Any: it switches checking off, which removes the benefit of the hint.
  • Confusing a hint with a conversion: age: int = input() does not make the value an integer. Call int().
  • Writing -> None and then returning a value: a function that returns something needs a matching return hint.
  • Using a mutable default value: a default such as items: list[str] = [] is shared between calls. Use None and create the list inside the function.
  • Mixing old and new syntax without a reason: prefer list[int] and int | None over List[int] and Optional[int] in new code.

Key Takeaways

Type hints make Python code easier to read, easier to maintain, and easier to check, and they work together with the editor and the type checker that you use. They cost very little to add, and they pay back every time someone has to understand a function a few months later. The points below summarize this lesson, and they prepare you for the next lesson on asynchronous Python, where you will learn to write programs that wait for slow tasks without freezing. Remember them whenever you write a new function.

  • A type hint is a label such as x: int or -> str that documents the expected type of a variable, a parameter, or a return value.
  • Python does not enforce type hints when the program runs. Tools such as mypy and Pyright check them.
  • Use list[int], dict[str, float], set[str], and tuple[str, int] to describe what is inside a container.
  • Use X | None for a value that may be missing, and int | str for a value that may have several types.
  • Type aliases give long types a short name, and Literal restricts a value to a few exact choices.
  • TypeVar describes functions that work with any type, and Callable describes functions that are passed around as values.
  • The hints are stored in __annotations__ and can be read with get_type_hints(), which is how dataclasses and many libraries use them.

Frequently Asked Questions

These are the questions that students ask most often when they learn about type hints in Python. The answers are brief and practical, and each idea appears in one of the examples above. If something is still unclear, try adding hints to one of your own older functions, and then pass it a wrong value on purpose to see that Python still runs it, while a type checker in your editor shows a warning.

What are type hints in Python?

Type hints, also called type annotations, are labels that describe the expected type of a variable, a function parameter, or a return value, for example age: int or def greet(name: str) -> str. They document the code and let editors and type checkers find mistakes, but Python does not enforce them at runtime.

Does Python enforce type hints?

No. The interpreter stores the hints but ignores them while the program runs, so a function annotated with int still accepts a string. Static tools such as mypy and Pyright, and the checks in many code editors, read the hints and report mismatches before you run the program.

How do I write a type hint for a list or a dictionary?

Put the type of the items in square brackets after the container name. Write list[str] for a list of strings, dict[str, int] for a dictionary with string keys and integer values, and tuple[str, int] for a tuple that holds a string and then an integer. These forms work in modern Python without importing anything.

How do I hint that a value can be None?

Use the union operator, as in str | None, which means a string or None. Older code writes Optional[str] from the typing module, which means the same. When a value can be None, check for it with is None before you use it.

What is the difference between Optional and Union?

Union lists several possible types, such as Union[int, str] or int | str. Optional[X] is a shortcut for Union[X, None], so it means X or None. In new code, the pipe syntax X | None is shorter and preferred.

What is a type alias in Python?

A type alias is a short name for a longer or more complex type, created with a simple assignment such as Coordinates = tuple[float, float]. You can then use the alias in hints, which makes them shorter and easier to read and lets you change the type in one place.

How can I check type hints automatically?

Run a static type checker such as mypy or Pyright on your code, or turn on type checking in your editor. These tools read the hints without running the program and list the places where a value does not match its expected type. You can also read hints at runtime with typing.get_type_hints().

Should I add type hints to every function?

Hints are optional, but they are most valuable on the parameters and return values of functions that other code calls, and on the fields of classes. Small throwaway scripts do not need them. Adding hints gradually to the important parts of a project gives you most of the benefit with little work.

Ready for the next step?Learn how to write programs that wait for slow tasks without freezing.
Next: Asynchronous Python →