Python type system
Table of Contents
Python Type System
Python is a dynamically and strongly typed language. This means that while variable types are checked at runtime (dynamic), the interpreter does not allow operations on incompatible types without explicit conversion (strong).
This approach aligns with the philosophy of Duck Typing, where the suitability of an object for an operation is determined by its methods and properties rather than its explicit type.
Gradual Typing with Type Hints
To improve code reliability and maintainability, Python introduced optional static type hints (starting with PEP 484). This allows Python to function as a gradual typing system, where developers can introduce static type checks into a dynamic codebase at their own pace.
These type hints:
- Are ignored by the Python interpreter at runtime.
- Are used by third-party static analysis tools like
Mypyto catch type errors before execution. - Improve code readability and serve as a form of documentation.
The typing module provides the necessary components for these hints, such as List, Dict, Tuple, Optional, and Any.
Example:
# A function without type hints def add_numbers(a, b): return a + b # The same function with type hints def add_numbers_typed(a: int, b: int) -> int: return a + b # A static type checker would flag this as an error # add_numbers_typed(5, "hello")