Type Hints for Python (Backport)
The `typing` library provides type hints for Python. The `typing` *package* on PyPI (version 3.10.0.0) is a backport of the standard library `typing` module, designed specifically for Python versions older than 3.5. It allows developers to add type annotations to their code for improved readability, maintainability, and static analysis by tools like MyPy. The `typing` *module* became a standard part of Python 3.5 (PEP 484) and has since received continuous enhancements and new features in subsequent Python releases. The PyPI package's versioning often reflects the Python version whose typing features it aims to backport.
Warnings
- gotcha Installing the `typing` PyPI package on Python 3.5 or later has *no effect* because the standard library `typing` module takes precedence. In some scenarios (e.g., `pip install -t . typing`), it can even cause `AttributeError` by shadowing the standard library module.
- deprecated For built-in generic types like `list`, `dict`, `set`, and `tuple`, using their `typing` module counterparts (e.g., `typing.List`, `typing.Dict`) is deprecated since Python 3.9.
- gotcha Type hints are primarily for static analysis tools (type checkers like MyPy, IDEs) and are *not* enforced by the Python runtime by default. Incorrect type hints will not cause runtime errors but will be flagged by static analyzers.
- deprecated `typing.Callable` is deprecated for runtime type checking in some contexts. While still commonly used for type annotations, `collections.abc.Callable` may be preferred for runtime checks where strict compatibility is desired, or when working with `isinstance` checks.
- breaking `typing.NewType` changed from a function to a class in Python 3.10, which introduced a slight runtime overhead. This change was reverted in Python 3.11, restoring performance to Python 3.9 levels. Code relying on the exact type or performance of `NewType` instantiation in 3.10 could be affected.
- gotcha Relying on internal `typing` module attributes (e.g., `__union_params__`) prior to Python 3.8 was risky due to the module's provisional status and led to breaking changes. Public APIs like `get_args()` were introduced to provide stable access.
Install
-
pip install typing -
pip install "typing; python_version < '3.5'"
Imports
- List
from typing import List
- Dict
from typing import Dict
- Optional
from typing import Optional
- Union
from typing import Union
- Callable
from typing import Callable
- Any
from typing import Any
Quickstart
from __future__ import annotations # For Python < 3.9, enables future syntax for type hints
from typing import List, Union, Optional
def greet(name: str) -> str:
return f"Hello, {name}!"
def get_item(items: List[str], index: int) -> Optional[str]:
if 0 <= index < len(items):
return items[index]
return None
def process_value(value: Union[int, str]) -> str:
if isinstance(value, int):
return f"Received an integer: {value}"
return f"Received a string: {value}"
print(greet("Alice"))
print(get_item(["apple", "banana"], 0))
print(get_item(["apple", "banana"], 2))
print(process_value(123))
print(process_value("hello"))