Welcome to type_templating’s documentation!

C++-style type templating for python

class type_templating.Template(*args, **kwargs)[source]

The main mechanism for declaring template types.

The result of type(SomeTemplate).

Use as:

T = TemplateParameter('T')
N = TemplateParameter('N')

# Sequence is a template taking one argument
class Sequence(metaclass=Template[T]):

# MyList is a template taking two arguments, where the first
# is passed down for use in the `Sequence` base class.
class MyList(Sequence[T], metaclass=Template[T, N]):
    def __init__(self, value=None):
        # self.__args contains the arguments values
        T_val = self.__args[T]
        N_val = self.__args[N]
        if value is None:
            self.value = [T_val()] * N_val
            assert len(value) == N_val
            self.value = value

    def __newinferred__(cls, value):
        ''' This is used to infer type arguments '''
        T_val = type(value[0])
        N_val = len(value)
        return cls[T_val, N_val](value)

assert isinstance(MyList, Template)

m = MyList[int, 3]()
assert isinstance(m, MyList[int, 3])
assert isinstance(m, MyList)
assert isinstance(m, Sequence[int])
assert isinstance(m, Sequence)

m = MyList(["Hello", "World"])
assert isinstance(m, MyList[str, 2])

The class definition use to define this template. Note that this is simply used as a base class, hence why it appears under this attribute. The base classes declared in the class definition will end up either in __expr_bases__ or __base__.__bases__.


The list of template parameters taken by this template


The list of TemplateExpressions which should be expanded with the template parameters.

class type_templating.TemplateParameter(name)[source]

A parameter used in a template specification.

Name is used only for display purposes

class type_templating.TemplateExpression(template, args)[source]

The result of SomeTemplate[T] or SomeTemplate[T, 1]

Note that this is not used if the full set of arguments are specified.


The version of this package

Indices and tables