typing-inspection

0.4.2 · active · verified Sat Mar 28

typing-inspection provides runtime tools to inspect Python type annotations at runtime. Maintained by the Pydantic team, it is split into two submodules: `typing_inspection.typing_objects` (predicate functions like `is_union`, `is_literal`, `is_any`, etc. that correctly handle both `typing` and `typing_extensions` variants) and `typing_inspection.introspection` (higher-level helpers such as `inspect_annotation`, `get_literal_values`, and `is_union_origin`). Current version is 0.4.2 (released 2025-10-01); the project has released frequently since its initial release in February 2025.

Warnings

Install

Imports

Quickstart

Inspect a ClassVar[Annotated[int, 'meta']] annotation, then use typing_objects predicates on the unwrapped type expression.

from typing import ClassVar, Union, get_origin
from typing import Annotated
from typing_inspection.introspection import (
    AnnotationSource,
    UNKNOWN,
    inspect_annotation,
    get_literal_values,
    is_union_origin,
)
from typing_inspection.typing_objects import is_any, is_literal, is_union

# --- Unwrap an annotation expression ---
result = inspect_annotation(
    ClassVar[Annotated[int, "meta"]],
    annotation_source=AnnotationSource.CLASS,
)
print(result)
# InspectedAnnotation(type=int, qualifiers={'class_var'}, metadata=['meta'])

# Check the UNKNOWN sentinel (bare ClassVar / Final with no inner type)
bare_result = inspect_annotation(ClassVar, annotation_source=AnnotationSource.CLASS)
if bare_result.type is UNKNOWN:
    print("No explicit inner type; infer from assignment or default to Any")

# --- typing_objects predicates handle both typing + typing_extensions ---
from typing import Literal
origin = get_origin(Literal[1, 2])
print(is_literal(origin))   # True

# Safe union detection across typing / typing_extensions / PEP 604
union_origin = get_origin(Union[int, str])
print(is_union_origin(union_origin))  # True

# Retrieve Literal values (expands PEP 695 type aliases correctly)
values = get_literal_values(Literal["a", "b", 1])
print(values)  # ('a', 'b', 1)

view raw JSON →