Python Type API for Type Hint Introspection
The `typeapi` package provides a unified and consistent API for the reflection and introspection of Python type hints. It enables evaluating future annotations such as PEP 585 (e.g., `list[str]`) and PEP 604 (e.g., `int | str`) in Python versions that do not natively support them. The current version is 2.3.0, and it maintains an active release cadence with regular updates.
Common errors
-
NameError: name 'list' is not defined
cause Attempting to use new-style generic type hints like `list[str]` directly in Python < 3.9 without `from __future__ import annotations` enabled.fixAdd `from __future__ import annotations` at the very top of your Python file. Alternatively, upgrade to Python 3.9 or newer, or use `typing.List[str]` for older Python versions if you do not want to use future imports. -
TypeError: 'type' object is not subscriptable
cause Trying to use generic types like `int | str` (PEP 604 union types) in Python < 3.10, or `list[str]` (PEP 585 generics) in Python < 3.9 without enabling `from __future__ import annotations`.fixEnsure `from __future__ import annotations` is at the top of your module. If targeting Python < 3.10 and not using future imports, use `typing.Union[int, str]`. For Python < 3.9, use `typing.List[str]`. -
AttributeError: 'TypeHint' object has no attribute 'non_existent_attribute'
cause Attempting to access properties or methods on a `TypeHint` object that do not exist or are not applicable to the specific type being introspected. For example, `is_optional` might be accessed incorrectly.fixConsult the `typeapi` documentation for the available attributes and methods of the `TypeHint` object and its sub-components (e.g., `ParameterTypeHint`). Ensure the attribute is valid for the context. Debug by printing `dir(type_hint_object)` to see available attributes.
Warnings
- gotcha When using Python versions older than 3.9, native generic type syntax like `list[str]` or `dict[str, int]` will raise `TypeError: 'type' object is not subscriptable` or `NameError: name 'list' is not defined` errors. `typeapi` is designed to parse these modern annotations, but for the Python interpreter to accept them, you either need Python 3.9+ or `from __future__ import annotations` (for runtime evaluation) in older versions.
- gotcha Python's type hints are primarily for static analysis and are not enforced at runtime by default. `typeapi` provides tools for *inspecting* these hints but does not perform runtime type checking or validation. Developers often mistakenly assume type hints add runtime validation.
Install
-
pip install typeapi
Imports
- TypeHint
from typeapi import TypeHint
Quickstart
from __future__ import annotations
from typeapi import TypeHint
from typing import Any
def process_items(items: list[str], limit: int | None = None) -> dict[str, Any]:
"""Example function with type hints to introspect."""
processed_data = {}
actual_limit = limit if limit is not None else len(items)
for i, item in enumerate(items[:actual_limit]):
processed_data[f"item_{i}"] = item.upper()
return processed_data
# Introspect the type hints of the function
function_type_hints = TypeHint.from_callable(process_items)
print(f"Function: {process_items.__name__}")
print(f" Parameters:")
for name, param_hint in function_type_hints.parameters.items():
print(f" - {name}: {param_hint.annotation} (is_optional={param_hint.is_optional})")
print(f" Return type: {function_type_hints.return_type.annotation} (is_generic={function_type_hints.return_type.is_generic})")
# Example of introspecting a standalone type (e.g., from a variable annotation)
my_type_var: dict[str, int | None]
standalone_type_hint = TypeHint.from_annotation(my_type_var.__annotations__['my_type_var'])
print(f"\nStandalone type: {standalone_type_hint.annotation}")
print(f" Is generic: {standalone_type_hint.is_generic}")
print(f" Origin: {standalone_type_hint.origin}")
# For generic types, you can access the arguments
if standalone_type_hint.is_generic:
print(f" Generic arguments: {standalone_type_hint.args}")