4.5.4. Templates#

class caterpillar.model.TemplateTypeVar(name: str, **field_kwds: Any)[source]#

Template type variable.

These specialised type variables are used within a template definition. They support most field operators. Therefore, they can be used in some situations where you need to adapt the field type at runtime.

>>> T = TemplateTypeVar("T")

Note that there is currently no support for inlined type variables, for example:

>>> @template(T)
... class Foo:
...     bar: Enum(Baz, T) # !!! throws an error

is not possible.

name: str#

The bound name of this type variable

field_kwds: dict[str, Any]#

Arguments that will be passed to the created field instance.

caterpillar.model.istemplate(obj: object) bool[source]#

Return true if the object is a template.

caterpillar.model.template(*args: str | TemplateTypeVar, **kwargs: str | TemplateTypeVar) Callable[[type[_TemplateModelT]], type[_TemplateModelT]][source]#

Defines required template type variables if necessary and prepares template class definition.

Returns:

a wrapper function that will be called with the class instance

Return type:

Callable[[type], type]

caterpillar.model.derive(template_ty: type, *tys_args: _StructLike, partial: bool = False, name: str | EllipsisType | None = None, union: bool = False, **tys_kwargs: _StructLike) type[source]#

Creates a new struct class based on the given template class.

Parameters:
  • template_ty (type) – the template class

  • partial (bool, optional) – whether the resulting class is also a template, defaults to False

  • name (str | Ellipsis, optional) – the new class name, ... infers the outer variable name, defaults to None

Returns:

the derived type

Return type:

type