Skip to main content

A python template engine

Project description

PyForma

A Python template engine featuring partial substitution.

Tests

Example

from pyforma import Template

template = Template("Hello, {{ subject }}! This is {{ lib_name }}.")
assert template.unresolved_identifiers() == {"subject", "lib_name"}

template = template.substitute({"lib_name": "PyForma"})
assert template.unresolved_identifiers() == {"subject"}

print(template.render({"subject": "World"}))  # Prints "Hello, World! This is PyForma."

Features

  • 100% Python
  • Python-like expressions in templates
  • Special-purpose environments for more expressive templates
  • Templates can be inspected for what variables need to be substituted
  • Can partially substitute variables within templates
  • Rendering with undefined variables results in an error
  • Fully statically typed

API

pyforma.Template(content, /, *, syntax)

The primary template class.

Parameters:

  • content: str | Path:
    If str, parses the string as a template.
    If Path, reads the file at that path and parses it as a template.
  • syntax: TemplateSyntaxConfig | None :
    Optional syntax definition.

Return Value:

Returns the template object.

Exceptions:

  • ValueError: The provided input is not a valid template.

pyforma.Template.unresolved_identifiers() -> set[str]

Reports all identifiers that need to be substituted to render the template.

Return Value:

Returns the set of all remaining identifiers in the template.

pyforma.Template.substitute(variables, *, keep_comments, renderers) -> Template

Partially substitutes variables in the template and evaluates expressions that can be evaluated.

Parameters:

  • variables: dict[str, Any]:
    Dictionary mapping variable identifiers to their values.
  • keep_comments: bool:
    By default, comments are kept until the final rendering. Set to False to strip all comments.
  • renderers: dict[type, Callable[[Any], str]] | None:
    Optional dictionary of renderers for stringification. By default, only str, int and float are rendered to str during template substitution. This argument can be used to automatically render additional types. Alternatively, the template needs to explicitly format other types as str.

Return Value:

A new template identical to self, but with the provided variables substituted.

Exceptions:

  • ValueError: An expression evaluates to a type that can not be rendered.

pyforma.Template.render(variables, *, renderers) -> str

Renders a template to a string.

Parameters:

  • variables: dict[str, Any] | None:
    Optional dictionary mapping variable identifiers to their values.
  • renderers: dict[type, Callable[[Any], str]] | None:
    Optional dictionary of renderers for stringification. See substitute() for details.

Return Value:

The rendered string with all variables substituted.

Exceptions:

  • ValueError:
    • Some unresolved variables remain after substitution.
    • An expression evaluates to a type that can not be rendered.

pyforma.TemplateSyntaxConfig(comment, expression, environment)

Template syntax configuration class.

Parameters:

  • comment: BlockSyntaxConfig:
    Configuration for comment blocks. Defaults to BlockSyntaxConfig("{#", "#}").
  • expression: BlockSyntaxConfig:
    Configuration for expression blocks. Defaults to BlockSyntaxConfig("{{", "}}").
  • environment: BlockSyntaxConfig:
    Configuration for environment blocks. Defaults to BlockSyntaxConfig("{%", "%}").

Exceptions:

  • ValueError: The configured symbols are not sufficiently distinct.

pyforma.BlockSyntaxConfig(open, close)

Class used for configuring the syntax of a block type.

Parameters:

  • open: str:
    Open block syntax. Must not be empty.
  • close: str:
    Close block syntax. Must not be empty.

Exceptions:

  • ValueError:
    • Either of the parameters is empty.
    • The provided parameters are identical.

Alternatives

  • Jinja2: The de-facto standard Python template engine. It's popular, fast, expressive and extensible, but doesn't support partial template substitution.
  • Mako: Compiles templates to Python bytecode.
  • Chameleon: HTML/XML-compatible template engine.
  • string.Template: The actual standard Python template engine. Pretty limited functionality.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyforma-0.2.0.tar.gz (17.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyforma-0.2.0-py3-none-any.whl (32.0 kB view details)

Uploaded Python 3

File details

Details for the file pyforma-0.2.0.tar.gz.

File metadata

  • Download URL: pyforma-0.2.0.tar.gz
  • Upload date:
  • Size: 17.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.8.22

File hashes

Hashes for pyforma-0.2.0.tar.gz
Algorithm Hash digest
SHA256 b8267df1f821556c14019e8c87ce58d37972feb7f9bb60ba8b8bf74d9b53b80e
MD5 404622ce3e3d8f994c7db7e861f03876
BLAKE2b-256 07489fa90d9749319de4d036a978adaec3a7b0451826450eea3d56a85bde0137

See more details on using hashes here.

File details

Details for the file pyforma-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: pyforma-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 32.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.8.22

File hashes

Hashes for pyforma-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a5769cd60f1323735f03c2abb656955948ddc21df7d680f3bec3a7658197c8b6
MD5 625f1f458c0efcfa175c88cb972cb915
BLAKE2b-256 fbbffcfff1cc99d57bb012984d98c146bf7f003b444c06d5dfd77c00ce5f48bb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page