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]): pass # 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 else: 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])
-
__base__
¶ 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__
.
-
__params__
¶ The list of template parameters taken by this template
-
__expr_bases__
¶ The list of
TemplateExpression
s 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]
orSomeTemplate[T, 1]
Note that this is not used if the full set of arguments are specified.
-
type_templating.
__version__
¶ The version of this package