API#
Builder#
- class templa.Builder(config, template_getter, parse_rendered_template, build_processed)#
Builder is the central class in Templa for executing build processes.
The Builder class defines the core logic of the build processes. It allows for method overriding and composition of functions to customize the build behavior. The data used in the build processes is provided from templa.Config.
Each build process and artifact fetching requires a self instance as the target of the builder, which is typed using the NewType returned from the previous build process. This ensures type safety and allows for the build processes to be executed sequentially.
Example:
builder = Builder(...) target_initialized = builder.init_builder_target() target_processed = builder.process_template(target_initialized) target_built = builder.build(target_processed) built = builder.fetch_built(target_built)
- Parameters:
PROCESSED – The Type parameter specifies the type of the parsed and rendered template.
BUILT – The Type parameter specifies the type of the built object.
config (Config[Any]) – An instance of templa.Config that provides the rendering context.
template_getter (TemplateGettable) – An implementation of the templa.TemplateGettable protocol that provides access to a jinja2.Template.
parse_rendered_template (Callable[[str], PROCESSED | None]) – Parse the rendered jinja2.Template and return the processed. The type of the processed is defined by the type parameter (PROCESSED) of templa.Builder.
build_processed (Callable[[PROCESSED | None], BUILT | None]) – Build an object of the type specified by the type parameter (BUILT) from the processed.
- property template_getter: TemplateGettable#
Returns a deepcopy of the provided template_getter instance.
- init_builder_target()#
Returns a NewType of the self instance as the initial builder target.
- Return type:
BuilderTargetInitialized
- fetch_render_context(target)#
Fetches and returns the rendering context from the self builder target. The rendering context is extracted from the provided templa.Config, which is used to render the template.
Raises templa.NotSameBuilderInstanceError if the self instance does not match the provided builder instance.
- Parameters:
target (BuilderTargetInitialized | BuilderTargetProcessed | BuilderTargetBuilt) – NewType of the self instance.
- Return type:
Dict[Any, Any]
- process_template(target)#
Calls _process_template() and returns a NewType of the builder target after processing the template.
Raises templa.NotSameBuilderInstanceError if the self instance does not match the provided builder instance.
- Parameters:
target (BuilderTargetInitialized) – NewType of the self instance.
- Return type:
BuilderTargetProcessed
- _process_template(context)#
Runs the template processing logic by obtaining the template, rendering it with the context provided by an instance of templa.Config as an argument, and parsing the rendered template.
Returns the parsed and rendered template.
- Parameters:
context (Dict[Any, Any]) – A deepcopy of the context passed to jinja2.Template.render().
- Return type:
PROCESSED | None
Intended to be overridden by a subclass. Example:
def _process_template(self, context: Dict) -> Optional[PROCESSED]: context.update({"zoo": "ZOO"}) return super()._process_template(context)
- fetch_processed(target)#
Fetches and returns the a deepcopy of the parsed and rendered template, which is created during the template processing step.
Raises templa.NotSameBuilderInstanceError if the self instance does not match the provided builder instance.
- Parameters:
target (BuilderTargetProcessed | BuilderTargetBuilt) – NewType of the self instance.
- Return type:
PROCESSED | None
- build(target)#
Calls _process_template() and returns a NewType of the builder target after building step.
Raises templa.NotSameBuilderInstanceError if the self instance does not match the provided builder instance.
- Parameters:
target (BuilderTargetProcessed) – NewType of the self instance.
- Return type:
BuilderTargetBuilt
- _build(processed)#
Runs the building logic to build the object using the parsed and rendered template generated during the template processing step.
Raises templa.NotSameBuilderInstanceError if the self instance does not match the provided builder instance.
Returns the built artifact.
- Parameters:
processed (PROCESSED | None) – A deepcopy of the parsed rendered template that is passed to jinja2.Template.render().
- Return type:
BUILT | None
Intended to be overridden by a subclass. Example:
def _build(self, processed: Optional[List[str]]) -> Optional[str]: if processed is not None: processed[2] = "ZOO_Updated" built_text = super()._build(processed) if built_text is None: return None with open("/tmp/built.txt", "w", encoding="utf-8") as f: f.write(built_text) return built_text
- fetch_built(target)#
Fetches and returns a deepcopy of the artifact generated during the building step.
Raises templa.NotSameBuilderInstanceError if the self instance does not match the provided builder instance.
- Parameters:
target (BuilderTargetBuilt) – NewType of the self instance.
- Return type:
BUILT | None
- exception templa.NotSameBuilderInstanceError#
An error that is raised when the builder instance passed as an argument for each build step method is different from the calling instance.
- templa.BuilderTargetInitialized = NewType("BuilderTargetInitialized", "Builder")#
NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:
UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int
A NewType of the builder instance as the initial target.
- templa.BuilderTargetProcessed = NewType("BuilderTargetProcessed", "Builder[Any, Any]")#
NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:
UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int
A NewType of the builder instance as the target after processing template.
- templa.BuilderTargetBuilt = NewType("BuilderTargetBuilt", "Builder[Any, Any]")#
NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:
UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int
A NewType of the builder instance as the target after building step.
Config#
- class templa.ConfigData#
A simple dataclasses.dataclass with frozen set to True to ensure integrity.
- class templa.Config(raw_config_dict, ConfigDataClass)#
Provides a template rendering context created from a dataclass. It can be accessed and modified as needed by overriding. The dataclass is created from a dictionary provided as an argument.
- Parameters:
CONFIG_DATA – The Type parameter specifies the type of the ConfigData instance.
raw_config_dict (Dict[Any, Any]) – A variadic argument for ConfigDataClass.
ConfigDataClass (Type[CONFIG_DATA]) – A ConfigData class.
- property raw_config_dict: Dict[Any, Any]#
Returns a deep copy of the provided raw_config_dict.
- load_config()#
Creates a ConfigData instance using the Config.raw_config_dict.
- Return type:
None
- property data: CONFIG_DATA | None#
Returns a ConfigData instance created by Config.load_config(). The frozen option of the returned ConfigData instance is set to True, which means it does not use deepcopy.
- get_render_context()#
Calls Config._get_render_context() and returns the returned context.
- Return type:
Dict[Any, Any]
- _get_render_context(data)#
Returns a dictionary created from the provided ConfigData instance. If the instance is None, an empty dictionary is returned.
Intended to be overridden by a subclass.
def _get_render_context(self, data: Optional[BarConfigData]) -> Dict: context = super()._get_render_context(data) context.update({"zoo": "ZOO"}) return context
- Parameters:
data (CONFIG_DATA | None) – ConfigData instance created by Config.load_config().
- Return type:
Dict[Any, Any]
- exception templa.ConfigDataNotLoadedError#
Used when a ConfigData instance is not created properly.
YAMLBuilder#
- class templa.YAMLBuilder(config, yaml_template_getter)#
Subclass of templa.Builder that uses templa.OrderedDictLoader and templa.OrderedDictDumper. Receives and renders a YAML template, and builds YAML while preserving the order of the received YAML.
- Parameters:
PROCESSED – The Type parameter specifies the type of the parsed and rendered template.
config (Config[Any]) – An instance of templa.Config that provides the rendering context.
yaml_template_getter (TemplateGettable) – An implementation of the templa.TemplateGettable protocol that provides access to a jinja2.Template which provides YAML template.
- class templa.OrderedDictLoader(stream)#
Subclass of yaml.Loader using OrderedDict collection as a constructor.
- class templa.OrderedDictDumper(stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True)#
Subclass of yaml.Dumper using OrderedDict collection as a representer.