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.3.0.tar.gz (19.7 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.3.0-py3-none-any.whl (35.3 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pyforma-0.3.0.tar.gz
Algorithm Hash digest
SHA256 0499fbe7ecaed208d519c754efc3241b10c4d4e4a4a28fab679a67abbd87efb3
MD5 698d01b06e0ffff68c7c78471a719297
BLAKE2b-256 058a88afb08eb472d6dea0f2fa3171b655fd1675a66d2aa4d0ae80a413df735a

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for pyforma-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4f8f5ff5af1908e510a2809c78463ab0f3149fd59ef406369c2af29cede0dd8e
MD5 f4a9977308deb1d83924ca8d78d567f3
BLAKE2b-256 c237b3437d7c71d8294e3f6a86c36b5eeb2bb0907c3353b12ffa341f15cd37ec

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