Python Type API for Type Hint Introspection

2.3.0 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `typeapi.TypeHint.from_callable` to extract and analyze type hints from a function. It then shows how to inspect a standalone type annotation using `TypeHint.from_annotation`. The example highlights accessing parameter details, return type, and generic type properties like origin and arguments.

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}")

view raw JSON →