typing | Python Standard Library – Real Python

Python’s typing module provides tools for adding type hints to your code. Type hints make your programs more readable, safer to refactor, and help static type checkers catch errors before runtime.

This module is a cornerstone of Python’s gradual typing system, allowing for enhanced code clarity and static analysis.

Here’s a quick example:

Key Features

  • Supports type hinting for variables, functions, and classes
  • Allows for custom type creation using TypeVar and NewType
  • Supports defining reusable type aliases for better code readability
  • Enables complex type definitions
  • Supports defining structural subtyping interfaces with protocols

Frequently Used Classes and Functions

Examples

Define a class using NamedTuple and a function that takes it as an argument:

Define a type alias to simplify complex type annotations:

Create a protocol and implement it in a class:

Common Use Cases

  • Specifying expected types for function parameters and return values
  • Defining complex data structures with precise type information
  • Enhancing code readability and maintainability
  • Assisting static type checkers like mypy in identifying potential errors

Real-World Example

Imagine you’re building an order processing system where you want to apply discounts to products. Using the typing module, you can create distinct type aliases, type variables, and callables to make your code safer and more expressive:

This example shows how to use NewType to create a type for order IDs and Callable to define a flexible function signature for discounts. These type hints make the order processing code more robust and maintainable.

Tutorial

Python Type Checking (Guide)

In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.

intermediate best-practices

For additional information on related topics, take a look at the following resources: