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.
  • OSError: If a path is passed and the file cannot be opened

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: Sequence[tuple[type, Callable[[Any], str]]] | None:
    Optional sequence 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: Sequence[tuple[type, Callable[[Any], str]]] | None:
    Optional sequence 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.4.0.tar.gz (20.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.4.0-py3-none-any.whl (35.9 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pyforma-0.4.0.tar.gz
Algorithm Hash digest
SHA256 80725095fc15d3ef14e2c7a38256910b52d658357c825c3441cdfd7b67403834
MD5 4ad269205f3f41899206d7ac6b1c1247
BLAKE2b-256 151531a8034a88a7d4b272f8f83fc596d3ac243baa39ee256fd97f7ccf9d98be

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for pyforma-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f7ef6b3ac49e613d91608e79fc6fec36ce0ed4dc39a8340fc0965290b7b2c8fb
MD5 f3917a76e605fd6c9cda8bb6b471815d
BLAKE2b-256 ed3368fdb40a5f32f66a5aeb75a4f5e6f02b508a3324bd78f9b22e451ff9f0dd

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