get_typing_args

get_typing_args#

tollan.utils.typing.get_typing_args(cls: Any, max_depth: int | None = 1, bound: type | None = None, type_filter: type | None = None, *, unique: bool = False) Any[source]#

Extract typing arguments from a class’s generic base classes.

Recursively traverses the class hierarchy to find all typing arguments from Generic base classes. Can filter results by bound (subclass check) or type_filter (instance check).

Parameters:
  • cls (Any) – Class or type construct to extract typing arguments from

  • max_depth (int | None, optional) – Maximum depth to traverse the class hierarchy. None means unlimited. Default is 1.

  • bound (type | None, optional) – Filter results to only include classes that are subclasses of this type

  • type_filter (type | None, optional) – Filter results to only include instances of this type

  • unique (bool, optional) – If True, expect exactly one result and return it directly (not a list). Raises ValueError if multiple or no results found.

Returns:

List of typing arguments found, or single argument if unique=True

Return type:

list[Any] | Any

Raises:

ValueError – If both bound and type_filter are specified, or if unique=True but result is not exactly one element

Examples

>>> from typing import Generic, TypeVar
>>> from pydantic import BaseModel
>>> T = TypeVar('T')
>>> class MyHandler(Generic[T]):
...     pass
>>> class MyConfig(BaseModel):
...     pass
>>> class ConcreteHandler(MyHandler[MyConfig]):
...     pass
>>> get_typing_args(ConcreteHandler, bound=BaseModel)
[<class '...MyConfig'>]
>>> get_typing_args(
...     ConcreteHandler, bound=BaseModel, unique=True
... )
<class '...MyConfig'>

Notes

This function is useful for automatically inferring type parameters from Generic base classes, particularly for frameworks that use Generic[T] patterns for dependency injection or configuration.