← Back to Python Course | Chapter 11: Advanced Python | Lesson 8 of 12

Python Type Hints

Type hints are labels that say what kind of value a variable or function expects, like writing sugar on a jar. Python does not enforce them, but they help people and tools spot mistakes.
Syntax
python
def function_name(parameter: type) -> return_type:
    # body

variable: type = value

What are Type Hints?

Type hints, introduced in Python 3.5 via PEP 484, are annotations that document a variable's or parameter's expected type without changing how the code actually runs -- Python's interpreter still ignores them at runtime.

Their real value is upfront: editors and IDEs use them for accurate autocomplete, and static checkers use them to catch type mistakes before you ever run the code.

Example: What are Type Hints?

python
def add(a: int, b: int) -> int:  # hints document expected types, ignored at runtime
    return a + b

print(add(2, 3))

Function Parameter Type Hints

Annotating a function signature means writing param: Type for each parameter and -> ReturnType right before the closing colon of the def line.

This makes a function's contract explicit at a glance, without needing to read its implementation or docstring to know what it expects and returns.

Example: Function Parameter Type Hints

python
def greet(name: str) -> str:  # name must be a str, function returns a str
    return f"Hello, {name}"

print(greet("Alex"))

Type Hinting Floating-Point Variables

Simple scalar hints like float or bool are the easiest place to start, since they document intent for values that would otherwise be ambiguous from a bare variable name alone.

They cost nothing at runtime and immediately make numeric or flag-like variables self-explanatory to anyone reading the code later.

Example: Type Hinting Floating-Point Variables

python
price: float = 19.99  # type hint documents this as a float
is_active: bool = True  # type hint documents this as a bool
print(price, is_active)

Complex Types from typing Module

For anything beyond simple scalars -- lists, dicts, tuples, or unions of several types -- you import generic types like List, Dict, and Tuple from the typing module (or use built-in generics directly in Python 3.9+, e.g. list[int]).

This lets you express structured shapes like 'a list of strings' or 'a dict mapping names to ages' precisely.

Example: Complex Types from typing Module

python
from typing import List, Dict

names: List[str] = ["Alex", "Sam"]  # a list of strings
ages: Dict[str, int] = {"Alex": 30}  # a dict mapping strings to ints
print(names, ages)

Benefits of Type Hints

Tools like mypy read your type hints and statically analyze your codebase for type mismatches -- passing a string where an int is expected, for instance -- without ever running the program.

Catching these errors before deployment is especially valuable in larger codebases where a wrong type can silently propagate for a long time before it causes a visible bug.

Example: Benefits of Type Hints

python
def add(a: int, b: int) -> int:
    return a + b

# A type checker like mypy would flag this at analysis time:
# add("2", 3)
print(add(2, 3))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting type hints to be enforced at runtime, when Python ignores them and add("a", "b") still runs.
  2. Writing list[int] on very old Python versions before 3.9, which raises TypeError; use typing.List[int] there.
  3. Returning a value that does not match the hint, such as -> int on a function that returns a string, which only a checker such as mypy will report.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.