Browse Python Topics ▼
Pick a Web Framework

Type Hints and Static Typing

📂 Advanced Python 📘 Lesson 45 of 57

Write robust, self-documenting code with Python type annotations. Learn variable and function signatures, generic collections, union types (int | None), and static type checking with mypy.

For the first twenty-five years of Python’s existence, the language was purely dynamically typed. You never declared types: a variable could hold an integer on line 1, a string on line 5, and a list on line 10.

While dynamic typing makes prototyping fast, it causes serious maintenance headaches in large software projects:

  • You encounter an unfamiliar function in your codebase:
    def notify_customer(customer, message):
        pass
  • What is customer? Is it an integer user ID (1042)? A string email ("alex@example.com")? Or a complex User object?
  • What happens if you pass the wrong type? The function might run for five minutes before crashing midway through with an unexpected AttributeError!

To solve this, Python 3.5+ introduced Type Hints (also known as Type Annotations).


1. The Crucial Fact: Python is STILL Dynamically Typed!

Before writing a single type hint, you must understand one fundamental rule:

Python’s runtime interpreter completely ignores type hints!

If you annotate a function expecting an integer and pass a string:

def double(number: int) -> int:
    return number * 2

# Python will NOT crash! It executes normally:
print(double("Cat"))  # 'CatCat' (String repetition!)

If Python Ignores Them, Why Use Type Hints?

  1. Instant IDE Autocomplete & Tooltips: Modern editors (VS Code, PyCharm) give you rich autocomplete suggestions and parameter documentation as you type.
  2. Crystal-Clear Self-Documentation: You never have to guess what a function expects or returns.
  3. Static Type Checking (mypy, pyright): External static analysis tools scan your entire codebase in seconds to catch bugs, typos, and incompatible types before your code ever deploys to production!

2. Basic Type Annotation Syntax

Annotating Variables

Use a colon (:) followed by the type name:

username: str = "alex_dev"
user_id: int = 42
account_balance: float = 1250.75
is_verified: bool = True

Annotating Functions

Annotate parameters with colons and return types with an arrow (->):

def calculate_tax(subtotal: float, tax_rate: float = 0.08) -> float:
    """Calculate sales tax for a transaction."""
    return subtotal * tax_rate

3. Generic Collections (Python 3.9+)

In modern Python (3.9+), built-in collection types support type parameters directly using square brackets [...]:

# A list containing ONLY strings:
skills: list[str] = ["Python", "FastAPI", "SQL"]

# A dictionary with string keys and float values:
stock_prices: dict[str, float] = {
    "AAPL": 178.50,
    "GOOG": 142.20
}

# A tuple with exact, fixed types for each position:
user_record: tuple[str, int, bool] = ("Alex", 29, True)

# A set of unique integers:
visited_node_ids: set[int] = {101, 102, 103}

4. Union Types and Optional Values (Python 3.10+ Pipe Syntax)

In Python 3.10+, you can use the vertical pipe operator (|) to represent a value that could be one of multiple types:

Union Types

def parse_id(raw_identifier: str | int) -> int:
    """Accepts either a string or an integer ID and returns an int."""
    return int(raw_identifier)

Optional / Nullable Values

When a variable or parameter can be None, combine the type with None using the pipe:

def find_user_email(username: str) -> str | None:
    """Returns the email string if found, or None if user does not exist."""
    database = {"alex": "alex@example.com"}
    return database.get(username)

[!NOTE] In older Python code (Python 3.8 and earlier), you will often see Union[str, int] or Optional[str] imported from the typing module. In Python 3.10+, the pipe syntax (str | int and str | None) is universally preferred.


5. Catching Bugs Before Runtime with Mypy

To see the real superpower of type hints, install Python’s industry-standard static type checker, mypy:

pip install mypy

Suppose you have this file:

# bug_sample.py
def send_invoice(client_id: int, amount: float) -> str:
    return f"Sent ${amount:.2f} invoice to client #{client_id}"

# Bug: Accidentally swapped arguments!
send_invoice(250.0, 42)

If you run mypy bug_sample.py, mypy flags the error before you ever run the code:

bug_sample.py:6: error: Argument 1 to "send_invoice" has incompatible type "float"; expected "int"
bug_sample.py:6: error: Argument 2 to "send_invoice" has incompatible type "int"; expected "float"
Found 2 errors in 1 file (checked 1 source file)

Summary & Stage 11 Capstone

Congratulations on completing Stage 11: Advanced Python! You now wield the most sophisticated language features Python has to offer:

  1. Low-level iteration with Iterators and the Iteration Protocol.
  2. Memory-efficient streaming with Generators and yield.
  3. Non-invasive function enhancement with Decorators and functools.wraps.
  4. Deterministic resource management with Context Managers and with.
  5. Self-documenting static verification with Type Hints and Mypy.

Next, learn how to run multiple tasks simultaneously and build lightning-fast asynchronous applications in Stage 12, starting with concurrency.

Test your understanding of Type Hints and Static Typing

Quick interactive practice questions with instant feedback.

Take Quiz →