Typing Utils
typing-utils is a Python library providing utilities to inspect Python type annotations. It backports features found in Python 3.8+ for type inspection, including `issubtype`, `get_origin`, `get_args`, and `get_type_hints`. The current version is 0.1.0, released in May 2021, suggesting a maintenance release cadence.
Warnings
- breaking The 0.1.0 release introduced several fixes and behavior changes for `issubtype`, particularly concerning `Union`, `None` (as `type(None)`), `TypeVar` checking, and `Callable`. Users upgrading from pre-0.1.0 versions might observe different results for type comparisons that previously exhibited buggy behavior.
- gotcha The `get_type_hints` function, while powerful, has 'counterintuitive' behavior regarding its `globalns` and `localns` parameters, similar to how `eval()` and `exec()` work. Incorrect usage can lead to unexpected results, especially with forward references.
- deprecated Starting with Python 3.9, many common types from the standard `typing` module (e.g., `List`, `Dict`, `Set`, `Tuple`) are deprecated in favor of using native collection types directly (e.g., `list[str]`, `dict[str, int]`). While `typing-utils` can inspect these types, relying on the deprecated `typing` forms in your codebase might lead to linting warnings or compatibility issues with future Python versions or type checkers.
Install
-
pip install typing-utils
Imports
- issubtype
from typing_utils import issubtype
- get_origin
from typing_utils import get_origin
- get_args
from typing_utils import get_args
- get_type_hints
from typing_utils import get_type_hints
Quickstart
import typing
from typing_utils import issubtype, get_origin, get_args
# Using issubtype
assert issubtype(list, typing.Sequence) == True
assert issubtype(typing.List[int], list) == True
assert issubtype(list, typing.List[int]) == False
# Using get_origin
assert get_origin(typing.List[int]) == list
assert get_origin(list) == list
# Using get_args
assert get_args(typing.List[int]) == (int,)
assert get_args(typing.Dict[str, float]) == (str, float)
print("Typing utilities working correctly!")