API reference

mstache module.

This module alone implements the entire mstache library, including its minimal command line interface.

The main functions are considered to be cli(), render() and stream(), and they expose different approaches to template rendering: command line interface, buffered and streaming rendering API, respectively.

Other functionality will be considered advanced, exposing some implementation-specific complexity and potentially non-standard behavior which could reduce compatibility with other mustache implementations and future major mstache revisions.

mstache.tokenize(template, *, tags=(b'{{', b'}}'), comments=False, cache={}, cache_make_key=<class 'tuple'>, keep_lines=False, strict=False)[source]

Compile mustache template as a tuple of token tuples.

Parameters:
Return type:

tuple[tuple[bool, bool, bool, bytes, bytes, int], ...]

Returns:

tuple of token tuples

Raises:

Added in version 0.3.0: keep_lines to disable tag-only-line collapsing, strict to disable compatability workarounds

mstache.stream(template, scope, *, scopes=(), resolver=<function default_resolver>, getter=(<function default_getter>, <function default_strict_getter>), stringify=<function default_stringify>, escape=<function default_escape>, lambda_render=<function default_lambda_render>, tags=(b'{{', b'}}'), cache={}, cache_make_key=<class 'tuple'>, recursion_limit=1024, keep_lines=False, strict=False)[source]

Generate rendered mustache template chunks.

Parameters:
Return type:

Generator[TypeVar(TString, bound= str | bytes), None, None]

Returns:

generator of bytes/str chunks (type depends on template)

Raises:

Added in version 0.3.0: getter support for mstache.PropertyGetterTuple, keep_lines to disable block-line stripping, strict to disable compatability workarounds

mstache.render(template, scope, *, scopes=(), resolver=<function default_resolver>, getter=(<function default_getter>, <function default_strict_getter>), stringify=<function default_stringify>, escape=<function default_escape>, lambda_render=<function default_lambda_render>, tags=(b'{{', b'}}'), cache={}, cache_make_key=<class 'tuple'>, recursion_limit=1024, keep_lines=False, strict=False)[source]

Render mustache template.

Parameters:
Return type:

TypeVar(TString, bound= str | bytes)

Returns:

rendered bytes/str (type depends on template)

Raises:

Added in version 0.3.0: getter support for mstache.PropertyGetterTuple, keep_lines to disable tag-only-line collapsing, strict to disable compatability workarounds

mstache.cli(argv=None)[source]

Render template from command line.

Use python -m mstache --help to check available options.

Parameters:

argv (Sequence[str] | None) – command line arguments, sys.argv when None

Return type:

None

exception mstache.TokenException[source]

Bases: SyntaxError

Invalid token found during tokenization.

classmethod from_template(template, start, end=None)[source]

Create exception instance from parsing data.

Parameters:
  • template (bytes) – template bytes

  • start (int) – character position where the offending tag starts at

  • end (int | None) – character position where the offending tag ends at

Return type:

TokenException

Returns:

exception instance

mstache.ClosingTokenException

Deprecated since version 0.3.0: Use SectionException instead.

exception mstache.SectionException[source]

Bases: TokenException

Section error found during tokenization.

Added in version 0.3.0.

exception mstache.UnopenedSectionException[source]

Bases: SectionException

Closing unknown section during tokenization.

Added in version 0.3.0.

exception mstache.UnclosedSectionException[source]

Bases: SectionException

Section left unclosed during tokenization.

Added in version 0.3.0.

exception mstache.UnclosedTokenException[source]

Bases: TokenException

Token left unclosed during tokenization.

exception mstache.DelimiterTokenException[source]

Bases: TokenException

Invalid delimiters token found during tokenization.

Added in version 0.1.1.

exception mstache.TemplateRecursionError[source]

Bases: RecursionError

Template rendering exceeded maximum render recursion.

mstache.default_recursion_limit = 1024

Default number of maximum nested renders.

A nested render happens whenener the lambda render parameter is used or when a partial template is injected.

Meant to avoid recursion bombs on templates.

mstache.default_resolver(name)[source]

Mustache partial resolver function (stub).

Parameters:

name (Any) – partial template name

Return type:

None

Returns:

None

mstache.default_getter(scope, scopes, key, default=None, *, virtuals=mappingproxy({'length': <function virtual_length>}))[source]

Extract property value from scope hierarchy retrying until full match.

Parameters:
  • scope (Any) – uppermost scope (corresponding to key '.')

  • scopes (Sequence) – parent scope sequence

  • key (str | bytes) – property key

  • default (Any) – value will be used as default when missing

  • virtuals (Mapping[str, Callable[[Any], Any]]) – mapping of virtual property callables

  • strict – disable compatibility workarounds

Return type:

Any

Returns:

value from scope or default

Both AttributeError and TypeError exceptions raised by virtual property implementations will be handled as if that property doesn’t exist, which can be useful to filter out incompatible types.

Added in version 0.1.3: virtuals parameter.

mstache.default_strict_getter(scope, scopes, key, default=None, *, virtuals=mappingproxy({'length': <function virtual_length>}))[source]

Extract property value from scope hierarchy retrying until partial match.

Parameters:
  • scope (Any) – uppermost scope (corresponding to key '.')

  • scopes (Sequence) – parent scope sequence

  • key (str | bytes) – property key

  • default (Any) – value will be used as default when missing

  • virtuals (Mapping[str, Callable[[Any], Any]]) – mapping of virtual property callables

Return type:

Any

Returns:

value from scope or default

Both AttributeError and TypeError exceptions raised by virtual property implementations will be handled as if that property doesn’t exist, which can be useful to filter out incompatible types.

Added in version 0.3.0.

mstache.default_getter_tuple = (<function default_getter>, <function default_strict_getter>)

Tuple with each getter function for compatibility and strict modes.

Items:

See also

default_getter()

Default getter implementation referenced by this tuple.

Added in version 0.3.0.

mstache.default_stringify(data, text)[source]

Convert arbitrary data to bytes.

Parameters:
  • data (Any) – value will be serialized

  • text (bool) – whether running in text mode or not (bytes mode)

Return type:

bytes

Returns:

template bytes

Changed in version 0.3.0: None to emit empty bytes

mstache.default_escape(data)[source]

Convert bytes conflicting with HTML to their escape sequences.

Parameters:

data (bytes) – bytes containing text

Return type:

bytes

Returns:

escaped text bytes

mstache.default_lambda_render(scope, **kwargs)[source]

Generate a template-only render function with fixed parameters.

Parameters:
  • scope (Any) – current scope

  • **kwargs – parameters forwarded to render()

Return type:

Callable[[TypeVar(TString, bound= str | bytes)], TypeVar(TString, bound= str | bytes)]

Returns:

template render function

mstache.default_tags = (b'{{', b'}}')

Tuple of default mustache tags as in tuple[bytes, bytes].

mstache.default_cache: CompiledTemplateCache = {}

Default template cache mapping, keeping the 1024 most recently used compiled templates (LRU expiration).

mstache.default_cache_make_key

Defaut template cache key function, tuple, so keys would be as in tuple[bytes, bytes, bytes, bool] containing the relevant mstache.tokenizer() parameters.

mstache.default_virtuals: Mapping[str, Callable[[Any], Any]] = mappingproxy({'length': <function virtual_length>})

Immutable mapping with default virtual properties.

The following virtual properties are implemented:

  • length, for non-mapping sized objects, returning len(ref).

mstache.Buffer: TypeAlias = str | bytes

String/bytes, string or bytes depending on text or binary mode.

Added in version 0.3.0.

class mstache.TString

String/bytes generic, string or bytes depending on text or binary mode.

alias of TypeVar(‘TString’, bound=str | bytes)

mstache.PartialResolver

Template partial resolver function interface.

See also

mstache.default_resolver()

Default partial resolver stub implementation.

alias of Callable[[str | bytes], str | bytes | None]

mstache.PropertyGetter

Template property getter function interface.

See also

mstache.default_getter()

Default non-strict getter implementation.

mstache.default_strict_getter()

Default strict getter implementation.

alias of Callable[[Any, Sequence, str | bytes, T], Any | T]

mstache.PropertyGetterTuple: TypeAlias = tuple[collections.abc.Callable[[typing.Any, collections.abc.Sequence, str | bytes, ~T], typing.Union[typing.Any, ~T]], collections.abc.Callable[[typing.Any, collections.abc.Sequence, str | bytes, ~T], typing.Union[typing.Any, ~T]]] | collections.abc.Sequence[collections.abc.Callable[[typing.Any, collections.abc.Sequence, str | bytes, ~T], typing.Union[typing.Any, ~T]]]

Tuple of property getter functions: non-strict and strict.

See also

mstache.PropertyGetter

Property getter function interface.

mstache.default_getter()

Default non-strict getter implementation.

mstache.default_strict_getter()

Default strict getter implementation.

mstache.StringifyFunction

Template variable general stringification function interface.

See also

mstache.default_stringify()

Default stringify-function implementation.

alias of Callable[[Any, bool], bytes]

mstache.EscapeFunction

Template variable value escape function interface.

alias of Callable[[bytes], bytes]

mstache.LambdaRenderFunctionConstructor: TypeAlias = collections.abc.Callable[..., collections.abc.Callable[..., str | bytes]] | None

Lambda render function constructor or None for implicit rendering.

Options:

  • collections.abc.Callable returning another callable which to be sent via render parameter to explicit (chevron-style) lambdas expecting both template content and render parameters.

  • None enables implicit rendering of lambda return values (spec-style) with lambdas only receving the template content as argument.

See also

mstache.default_lambda_render()

Default explicit lambda render constructor.

Changed in version 0.3.0: None for implicit return value render.

mstache.VirtualPropertyFunction

Virtual property implementation callable interface.

alias of Callable[[Any], Any]

mstache.VirtualPropertyMapping

Virtual property mapping interface.

See also

mstache.default_virtuals

Default mapping of virtual property functions.

alias of Mapping[str, Callable[[Any], Any]]

mstache.TagsTuple: TypeAlias = tuple[str | bytes, str | bytes] | collections.abc.Sequence[str | bytes]

Mustache tag tuple interface.

See also

mstache.default_tags

Default tuple of mustache template tags.

mstache.TagsByteTuple: TypeAlias = tuple[bytes, bytes] | collections.abc.Sequence[bytes]

Mustache tag byte tuple interface.

See also

mstache.default_tags

Default tuple of mustache template tags.

mstache.CompiledToken

Compiled template token.

Tokens are tuples containing a renderer decision path, key, content and flags.

a: bool

Decision for rendering path node a.

b: bool

Decision for rendering path node b.

c: bool

Decision for rendering path node c.

key: bytes

Template substring with token scope key.

content: bytes

Template substring with token content data.

flags: int

Token flags.

  • Unused: -1 (default)

  • Variable flags:
    • 0 - escaped

    • 1 - unescaped

  • Block start flags:
    • 0 - falsy

    • 1 - truthy

  • Block end value: block content index.

alias of tuple[bool, bool, bool, bytes, bytes, int]

mstache.CompiledTemplate

Compiled template interface.

See also

mstache.CompiledToken

Item type.

mstache.CompiledTemplateCache

Interface exposing this type.

alias of tuple[tuple[bool, bool, bool, bytes, bytes, int], …]

class mstache.CompiledTemplateCache(*args, **kwargs)[source]

Bases: Protocol

Cache object protocol.

See also

mstache.CompiledTemplate

Item type.

mstache.CacheMakeKeyFunction

Cache key function interface.

mstache.default_cache

Default cache instance.

get(key)[source]

Get compiled template from key, if any.

Return type:

tuple[tuple[bool, bool, bool, bytes, bytes, int], ...] | None

__setitem__(key, value)[source]

Assign compiled template to key.

Return type:

None

mstache.CacheMakeKeyFunction

Cache mapping key function interface.

See also

mstache.CompiledTemplateCache

Interface exposing this type.

mstache.default_cache_make_key()

Default implementation of cache make-key function.

alias of Callable[[tuple[bytes, bytes, bytes, bool, bool, bool]], Any]