ensure_cls_attr_from_type_args#
- tollan.utils.typing.ensure_cls_attr_from_type_args(cls: type, attr_name: str, max_depth: int = 2, bound: type | None = None, type_filter: type | None = None, *, skip_on_exist: bool = True, disallow_explicit: bool = True) None[source]#
Ensure a class attribute is set from typing arguments.
Extract typing arguments from the class’s generic base classes and set the specified class attribute to the first matching argument.
- Parameters:
cls (type) – Class to set attribute on
attr_name (str) – Name of the class attribute to set
max_depth (int, optional) – Maximum depth to traverse the class hierarchy. Default is 2.
bound (type | None, optional) – Filter typing arguments to only include subclasses of this type
type_filter (type | None, optional) – Filter typing arguments to only include instances of this type
skip_on_exist (bool, optional) – If True, do not overwrite the attribute if it already exists.
disallow_explicit (bool, optional) – If True, raise TypeError if the attribute is explicitly set on cls (not inherited). Forces use of type parameters for consistency. Default is True to enforce consistency.
- Raises:
TypeError – If disallow_explicit=True and attribute is explicitly set on cls.
ValueError – If no matching typing argument is found, or if multiple are found.
Notes
This function is useful for automatically setting class attributes based on Generic[T] type parameters, particularly in frameworks that use generics for configuration or dependency injection.
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 >>> ensure_cls_attr_from_type_args( ... ConcreteHandler, 'config_model_cls', bound=BaseModel ... ) >>> ConcreteHandler.config_model_cls <class '...MyConfig'>