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], andtuple[str, int]describe what is inside a container. - Optional and union types:
str | Noneandint | strallow more than one kind of value. - The
typingmodule: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.
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__)str after the name say that city is meant to hold text. The value "Austin" is assigned in the same line.int marks a whole number. The underscores in 979_882 are only a reading aid, and Python ignores them.float marks a number with a decimal part.bool marks a value that is either True or False. Austin is the capital of Texas.-> str after the parentheses says that the function returns text.:, adds thousands separators.Austin has 979,882 people.{'name': <class 'str'>, 'people': <class 'int'>, 'return': <class 'str'>}.float bool.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.
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__)price and rate are annotated as float, and the return value is also a float.Total: $21.65."ab" is not a float, but Python does not check. It evaluates "ab" * 3, because 1 + 2 is 3.ababab. No error occurred.str. A type checker would have flagged line 7.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.
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)scores must be a list of whole numbers, and the function returns a float./ always gives a float.tuple[str, int] promises two values: a string first and an integer second.players is declared as a list of strings.88.5.{'Jake': 4, 'Sophia': 6, 'Mason': 5}.city and people.Chicago 2746388.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.
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")str | None, which means a phone number as text, or None when the name is not found.get() method returns the value for the key, or None when the key is missing.code may be an integer or a string, as the hint int | str says.str() turns the value into text, and zfill(5) pads it with zeros on the left up to five characters.contacts maps names to phone numbers, and both are strings.555-0142.None. The output is None.02108.90210.phone may hold a string or None.is None is the correct way to check for a missing value.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.
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))Literal comes from the typing module.Coordinates now stands for a tuple of two floats, which is a latitude and a longitude.Size accepts only these three exact strings.size must be one of the three allowed strings, and the function returns a float.Coordinates, which is much shorter than writing the tuple type two times.Coordinates.3.45.From (47.61, -122.33) to (45.52, -122.68).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.
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__)dataclass decorator comes from the dataclasses module.@dataclass reads the annotated fields below and writes the __init__() method for us.Student describes one student record.name holds text and has no default, so it is required.grade holds the school year as a whole number and is also required.gpa is a float, and it has the default value 3.0.-> bool says.Student(name='Emma Davis', grade=11, gpa=3.8).True False, because 3.8 is at least 3.5 and 3.0 is not.{'name': <class 'str'>, 'grade': <class 'int'>, 'gpa': <class 'float'>}.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 typeT.Callable[[int, int], str]is a function with two integer parameters that returns a string.Anyturns 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.
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))Callable, Iterable, and TypeVar all come from the typing module.T is a placeholder for any one type. Whatever type it stands for must be the same everywhere in one call.T, the default is a T, and the result is a T as well.Callable[[float], float] says that rule is a function with one float parameter that returns a float.Boston.no cities.10.60.0.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.
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")get_type_hints() returns the hints of a function as a dictionary."TX", and a string return type.**values collects them in a dictionary.name to str, age to int, state to str, and return to str.isinstance() tells whether the value has the expected type, and the conditional expression picks the word OK or WRONG.name: OK (str vs str), age: WRONG (str vs int), and state: OK (str vs str).Tip: Add hints to the signatures of your functions first, because that is where they help the most. Use simple built-in types such aslist[str]anddict[str, int]before you reach fortypinghelpers, 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.
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)}")Great for 30 or more, Average for 20 or more, and Low otherwise.420, is converted from text to the float 420.0. The hint float documents the result.12, becomes 12.0.35.0 MPG - Great.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.
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}")burger, 3 is split at the comma into "burger" and " 3".strip() removes the extra space around the item name, and int() converts the quantity to a number. The function returns both values.float | None, which means a total or nothing.None.burger, 3 is stored as text.("burger", 3), which is assigned to name and count.cost may be a float or None, so the code tests it before using it.taco, the output is Sorry, taco is not on the menu.else branch runs.3 x burger = $26.97.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
listordict: it does not say what is inside. Writelist[str]ordict[str, int]. - Forgetting
Nonein the return type: a function that sometimes returns nothing needs-> str | None, and the caller must check forNone. - 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. Callint(). - Writing
-> Noneand 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. UseNoneand create the list inside the function. - Mixing old and new syntax without a reason: prefer
list[int]andint | NoneoverList[int]andOptional[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: intor-> strthat 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], andtuple[str, int]to describe what is inside a container. - Use
X | Nonefor a value that may be missing, andint | strfor a value that may have several types. - Type aliases give long types a short name, and
Literalrestricts a value to a few exact choices. TypeVardescribes functions that work with any type, andCallabledescribes functions that are passed around as values.- The hints are stored in
__annotations__and can be read withget_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.