Changelog¶
Unreleased changes
Changes not yet released are tracked in CHANGELOG.md in the repository.
v0.3.0 (2025-12-10)¶
This release introduces graph traversal capabilities with the walk() function and semantic edge metadata via edges().
Added¶
Graph traversal with walk()¶
A new walk() function for depth-first traversal of type graphs with predicate filtering and depth limiting.
Key features:
- Depth-first iteration yielding unique nodes (by object identity)
- Iterative implementation prevents recursion depth errors
- Optional
predicatefilter withTypeIssupport for type narrowing - Optional
max_depthparameter to limit traversal depth
Semantic edge metadata with edges()¶
A new edges() method on TypeNode that returns semantic edge metadata describing the relationship between parent and child nodes.
New types:
TypeEdge— Frozen dataclass containing edge metadata (kind, optional name, optional index)TypeEdgeKind— Enum with 25 semantic edge kinds (ELEMENT,KEY,VALUE,FIELD,PARAM,RETURN, etc.)TypeEdgeConnection— Frozen dataclass pairing aTypeEdgewith its targetTypeNode
Edge kinds by category:
| Kind | Description |
|---|---|
ELEMENT |
Tuple element (positional) |
KEY |
Dict key type |
VALUE |
Dict value type |
UNION_MEMBER |
Union variant |
ALIAS_TARGET |
Type alias target definition |
INTERSECTION_MEMBER |
Intersection member |
| Kind | Description |
|---|---|
FIELD |
Class/TypedDict field |
METHOD |
Class method |
PARAM |
Callable parameter |
RETURN |
Callable return type |
| Kind | Description |
|---|---|
ORIGIN |
Generic origin (list in list[int]) |
BOUND |
TypeVar bound |
CONSTRAINT |
TypeVar constraint |
DEFAULT |
TypeParam default |
BASE |
Class base class |
TYPE_PARAM |
TypeVar definition |
TYPE_ARG |
Applied type argument |
SIGNATURE |
Function signature |
NARROWS |
TypeGuard/TypeIs target |
SUPERTYPE |
NewType supertype |
ANNOTATED_BASE |
Annotated[T, ...] base type |
META_OF |
Type[T] target |
TARGET |
Unpack[T] target |
PREFIX |
Concatenate prefix types |
PARAM_SPEC |
Concatenate ParamSpec |
RESOLVED |
ForwardRef resolved type |
VALUE_TYPE |
Enum value type |
Helper constructors:
TypeEdge.field(name)— Create aFIELDedge with the given nameTypeEdge.element(index)— Create anELEMENTedge with the given index
TraversalError exception¶
A new TraversalError exception raised when walk() encounters invalid parameters (e.g., negative max_depth).
Changed¶
children()is now O(1) — Thechildren()method on allTypeNodesubclasses is now backed by a pre-computed tuple, making repeated access constant-time rather than recomputing the child list on each call.
Documentation¶
Tutorials:
- Traversing type graphs — Introduction to graph traversal with
walk()
How-to guides:
- Filtering with walk() — Using predicates and depth limits to filter traversal
Explanations:
- Graph edges — Understanding semantic edge metadata and relationships
Updates to existing docs:
- Added
walk()reference to "Your first type inspection" tutorial - Added graph traversal section to "Architecture overview" explanation
v0.2.0 (2025-11-30)¶
This release introduces MetadataCollection, a powerful immutable container for querying and transforming type annotation metadata.
Added¶
MetadataCollection class¶
A new immutable, sequence-like container for working with type annotation metadata. The class provides a comprehensive API for querying, filtering, and transforming metadata extracted from Annotated types.
Core features:
- Full sequence protocol support (
__len__,__getitem__,__contains__,__iter__,__bool__,__reversed__) - Hashable when all contained metadata is hashable
EMPTYsingleton for representing empty collections- Truncated
__repr__for readable debugging output
Factory methods:
MetadataCollection.of(*items, auto_flatten=True)— Create from arbitrary metadata items with optionalGroupedMetadataflatteningMetadataCollection.from_annotated(annotated_type, *, recursive=False)— Extract metadata fromAnnotatedtypesflatten()— ExpandGroupedMetadataat the top levelflatten_deep()— Recursively expand all nestedGroupedMetadata
Query methods:
find(type_)— Find first metadata of exact type, returnsT | Nonefind_first(*types)— Find first metadata matching any of the given typesfind_all(*types)— Find all metadata matching given types (single type returnsMetadataCollection[T])has(*types)— Check if any metadata matches the given typescount(*types)— Count metadata items matching the given typesget(type_, default=...)— Get first metadata of type with optional defaultget_required(type_)— Get first metadata of type, raisingMetadataNotFoundErrorif not found
Filtering methods:
filter(predicate)— Filter by arbitrary predicate functionfilter_by_type(type_, predicate)— Type-safe filtering with typed predicatefirst(predicate=None)— Get first item optionally matching predicatefirst_of_type(type_, predicate=None)— Get first item of type optionally matching predicateany(predicate)— Check if any item matches predicatefind_protocol(protocol)— Find first item implementing a runtime-checkableProtocolhas_protocol(protocol)— Check if any item implements aProtocolcount_protocol(protocol)— Count items implementing aProtocol
Transformation methods:
__add__and__or__— Combine collections (both operators supported for ergonomics)exclude(*types)— Remove items of specified typesunique()— Remove duplicate items (preserves order)sorted(key=None)— Sort items with optional key functionreversed()— Reverse item ordermap(func)— Apply function to each item (terminal operation returninglist)partition(predicate)— Split into matching and non-matching collections
Introspection methods:
types()— Getfrozensetof all metadata types in collectionby_type()— Group metadata by type into a dictis_empty— Property indicating if collection has no itemsis_hashable()— Check if all items are hashable
Exceptions:
MetadataNotFoundError— Raised byget_required()when metadata is not foundProtocolNotRuntimeCheckableError— Raised whenProtocolmethods receive non-runtime-checkable protocols
Protocol:
SupportsLessThan— Protocol for items supporting<comparison, used bysorted()
Changed¶
Breaking changes¶
Breaking changes
This release includes breaking changes to the metadata API. MetadataCollection is fully backwards-compatible with tuple access patterns (indexing, iteration, length, containment), so most existing code will continue to work without modification.
-
TypeNode.metadatatype changed fromtuple[Any, ...]toMetadataCollection[Any]— The metadata property on allTypeNodesubclasses now returns aMetadataCollectioninstead of a plain tuple.MetadataCollectionis fully backwards-compatible with tuple access patterns (indexing, iteration, length, containment), but code using tuple-specific methods may need updates. -
FieldDef.metadatatype changed fromtuple[Any, ...]toMetadataCollection[Any]— Field definitions for dataclasses,TypedDict,NamedTuple, attrs, and Pydantic models now returnMetadataCollection. -
Parameter.metadatatype changed fromtuple[Any, ...]toMetadataCollection[Any]— Function parameter metadata now returnsMetadataCollection.
Documentation¶
Documentation has been reorganized following the Diataxis framework with four distinct content types:
Tutorials (learning-oriented):
- Your first type inspection — Introduction to inspecting type annotations
- Working with metadata — Using
MetadataCollectionfor metadata queries - Inspecting structured types — Exploring dataclasses,
TypedDict, andNamedTuple - Inspecting functions — Inspecting function types and parameters
How-to guides (goal-oriented):
- Querying metadata — Find, filter, and extract metadata from types
- Filtering metadata — Narrow down metadata with predicates and protocols
- Transforming metadata — Combine, sort, and reshape metadata collections
- Metadata recipes — Common patterns and advanced techniques
- Walking the type graph — Traverse and analyze type structures
- Configuration options — Customize inspection behavior
Explanations (understanding-oriented):
- Forward references — Reference resolution strategies and trade-offs
- Architecture overview — Design principles and internal structure
- Metadata and Annotated — How metadata extraction and hoisting works
- Union types — Union handling and normalization
- Type aliases — PEP 695 type alias support
- Generics and variance — Generic type handling and variance
- Qualifiers — Type qualifier extraction and representation
Reference (information-oriented):
- API reference reorganized into 11 logical sections with 122 public members
- Glossary with comprehensive terminology definitions
- Changelog with Keep a Changelog format
LLM context files:
llms.txt— Concise project summary for LLM context windowsllms-full.txt— Comprehensive documentation dump for detailed LLM assistance
v0.1.0 (2025-11-27)¶
This is the initial release of typing-graph, a Python library for inspecting type annotations and building graph representations of type metadata.
Added¶
Core type inspection¶
inspect_type()function for inspecting any Python type annotation with caching supportclear_cache()function to clear the global type inspection cacheget_type_hints_for_node()function to convertTypeNodeback to runtime type hints
Type node hierarchy¶
TypeNodeabstract base class withsource,metadata,qualifiers, andchildren()for graph traversalConcreteTypefor non-generic nominal types (int,str, custom classes)GenericTypeNodefor unsubscripted generic types (list,Dict)SubscriptedGenericfor generic types with applied arguments (list[int],Dict[str, T])UnionTypefor union types (A | B)TupleTypefor heterogeneous and homogeneous tuple typesCallableTypefor callable types with parameter and return type informationAnnotatedTypeforAnnotated[T, ...]when metadata is not hoisted
Special form nodes¶
AnyTypefortyping.AnyNeverTypefortyping.Neverandtyping.NoReturnSelfTypefortyping.SelfLiteralNodeforLiteral[...]with specific valuesLiteralStringTypefortyping.LiteralString(PEP 675)EllipsisTypefor ellipsis inCallable[..., R]andtuple[T, ...]
Type variable nodes¶
TypeVarNodeforTypeVarwith variance, bounds, constraints, and defaults (PEP 696)ParamSpecNodeforParamSpec(PEP 612)TypeVarTupleNodeforTypeVarTuple(PEP 646)ConcatenateNodeforConcatenate[X, Y, P]UnpackNodeforUnpack[Ts]Varianceenum for type variable variance (invariant, covariant, contravariant)
Forward reference handling¶
ForwardRefnode for string forward referencesRefStatewith Unresolved, Resolved, and Failed states- Three evaluation modes via
EvalMode: EAGER, DEFERRED, STRINGIFIED
Type narrowing nodes¶
TypeGuardTypefor TypeGuard[T] (PEP 647)TypeIsTypefor TypeIs[T] (PEP 742)MetaTypefor Type[T] and type[T]NewTypeNodefor NewType definitions
Type alias support¶
TypeAliasNodefor simple type aliasesGenericAliasfor PEP 695 parameterized type aliases (type Vector[T] = list[T])inspect_type_alias()function for inspecting type aliases
Structured type inspection¶
DataclassTypewithDataclassFieldDeffor dataclass introspectionTypedDictTypewith field requiredness trackingNamedTupleTypewith field definitionsProtocolTypewith methods and attributesEnumTypewith typed membersFieldDefbase class for field definitions
Class inspection¶
inspect_class()for auto-detecting and inspecting any class typeinspect_dataclass()for dataclass-specific inspectioninspect_enum()for enum-specific inspectionClassNodefor general class inspection with type parameters, bases, methods, and variables
Function inspection¶
inspect_function()for function introspection with signature detailsinspect_signature()for callable signature inspectionFunctionNodewith async, generator, and decorator detectionSignatureNodewith full parameter informationParameterclass with name, type, kind, default, and metadata
Module inspection¶
inspect_module()for discovering all public types in a moduleModuleTypesresult class containing classes, functions, type aliases, type vars, and constants
Configuration¶
InspectConfigfor controlling inspection behavior- Configurable forward reference evaluation mode
- Optional recursion depth limits
- Options for including private members, inherited members, methods, class vars, and instance vars
- Optional metadata hoisting from Annotated types
- Optional source location tracking
Type qualifier support¶
- Extraction and tracking of
ClassVar,Final,Required,NotRequired,ReadOnly, andInitVarqualifiers - Re-export of
Qualifierfrom typing-inspection
Source location tracking¶
SourceLocationclass withmodule,qualname,lineno, andfileattributes- Optional source location extraction for type definitions
Type guard functions¶
TypeIs-based type guard functions for all node types (is_type_node,is_concrete_type,is_union_type_node, etc.)
Python version support¶
- Python 3.10, 3.11, 3.12, 3.13, 3.13t, 3.14, and 3.14t