Typing Inspect
typing-inspect is a Python library providing runtime inspection utilities for types defined in the standard `typing` module. It is currently at version 0.9.0, is actively maintained, and compatible with Python 3.6 and later. It offers an easy-to-use API for advanced introspection of type hints.
Warnings
- breaking The API of `typing-inspect` is still considered experimental. While generally stable, breaking changes might occur in future versions. Users should consult the changelog for specific updates.
- gotcha There exists another, distinct library named `typing-inspection` (used by Pydantic) which provides similar runtime typing introspection tools. Ensure you are importing from `typing_inspect` (underscore) for this library, not `typing_inspection` (hyphen).
- gotcha The `get_args` function, when called with `evaluate=True`, can be computationally expensive in terms of both time and memory. This option performs all type parameter substitutions.
- gotcha `typing-inspect` is designed to work with the latest versions of the Python `typing` module and `typing-extensions`. Older or specific versions of these dependencies might lead to unexpected behavior or unsupported types.
Install
-
pip install typing-inspect
Imports
- is_generic_type
from typing_inspect import is_generic_type
- get_args
from typing_inspect import get_args
- get_origin
from typing_inspect import get_origin
- is_union_type
from typing_inspect import is_union_type
- is_optional_type
from typing_inspect import is_optional_type
Quickstart
from typing import List, Union, Optional, TypeVar
from typing_inspect import is_generic_type, get_args, get_origin, is_optional_type
T = TypeVar('T')
class MyGeneric(List[T]):
pass
# Example 1: Check if a type is generic
assert is_generic_type(MyGeneric[int]) # This should be True
assert not is_generic_type(int) # This should be False
# Example 2: Get arguments of a type
args = get_args(List[str])
assert args == (str,)
union_type = Union[int, str]
union_args = get_args(union_type)
assert set(union_args) == {int, str}
# Example 3: Get the origin of a type
origin = get_origin(List[int])
assert origin is list
# Example 4: Check for optional types
assert is_optional_type(Optional[int])
assert not is_optional_type(int)
print("All quickstart assertions passed!")