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.1.1.tar.gz (16.5 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.1.1-py3-none-any.whl (31.2 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pyforma-0.1.1.tar.gz
Algorithm Hash digest
SHA256 6065e0c24397612aa257373439d3c9c0e69b3550969ad51e855253b66a261d00
MD5 043135934e9f656ca1fe490f1e3982af
BLAKE2b-256 ce9792cae913ea145c72d78935049dd6f740adb538ec1ac3cc635c2ac5b7ce96

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for pyforma-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 248dbc6e44bed5ef9ad9849d3642d35f596b4b5cdcd101a433f75d9032382934
MD5 c7b4e968e8a75d1bdabfcb3a739bb5b2
BLAKE2b-256 9cadf18c82f1d8ee700829d8f465551e4a6f9da5ea7fe6fe3df1bba482586368

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