Skip to content
Myr

nativetypes.py

This file

Path

src/jinja2/nativetypes.py

130 lines · 4.1 KiB · Python

Last changed by

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

History of this file

Take it

1import typing as t2from ast import literal_eval3from ast import parse4from itertools import chain5from itertools import islice6from types import GeneratorType78from . import nodes9from .compiler import CodeGenerator10from .compiler import Frame11from .compiler import has_safe_repr12from .environment import Environment13from .environment import Template141516def native_concat(values: t.Iterable[t.Any]) -> t.Any | None:17    """Return a native Python type from the list of compiled nodes. If18    the result is a single node, its value is returned. Otherwise, the19    nodes are concatenated as strings. If the result can be parsed with20    :func:`ast.literal_eval`, the parsed value is returned. Otherwise,21    the string is returned.2223    :param values: Iterable of outputs to concatenate.24    """25    head = list(islice(values, 2))2627    if not head:28        return None2930    if len(head) == 1:31        raw = head[0]32        if not isinstance(raw, str):33            return raw34    else:35        if isinstance(values, GeneratorType):36            values = chain(head, values)37        raw = "".join([str(v) for v in values])3839    try:40        return literal_eval(41            # In Python 3.10+ ast.literal_eval removes leading spaces/tabs42            # from the given string. For backwards compatibility we need to43            # parse the string ourselves without removing leading spaces/tabs.44            parse(raw, mode="eval")45        )46    except (ValueError, SyntaxError, MemoryError):47        return raw484950class NativeCodeGenerator(CodeGenerator):51    """A code generator which renders Python types by not adding52    ``str()`` around output nodes.53    """5455    @staticmethod56    def _default_finalize(value: t.Any) -> t.Any:57        return value5859    def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:60        return repr("".join([str(v) for v in group]))6162    def _output_child_to_const(63        self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo64    ) -> t.Any:65        const = node.as_const(frame.eval_ctx)6667        if not has_safe_repr(const):68            raise nodes.Impossible()6970        if isinstance(node, nodes.TemplateData):71            return const7273        return finalize.const(const)  # type: ignore7475    def _output_child_pre(76        self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo77    ) -> None:78        if finalize.src is not None:79            self.write(finalize.src)8081    def _output_child_post(82        self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo83    ) -> None:84        if finalize.src is not None:85            self.write(")")868788class NativeEnvironment(Environment):89    """An environment that renders templates to native Python types."""9091    code_generator_class = NativeCodeGenerator92    concat = staticmethod(native_concat)  # type: ignore939495class NativeTemplate(Template):96    environment_class = NativeEnvironment9798    def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:99        """Render the template to produce a native Python type. If the100        result is a single node, its value is returned. Otherwise, the101        nodes are concatenated as strings. If the result can be parsed102        with :func:`ast.literal_eval`, the parsed value is returned.103        Otherwise, the string is returned.104        """105        ctx = self.new_context(dict(*args, **kwargs))106107        try:108            return self.environment_class.concat(  # type: ignore109                self.root_render_func(ctx)110            )111        except Exception:112            return self.environment.handle_exception()113114    async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:115        if not self.environment.is_async:116            raise RuntimeError(117                "The environment was not created with async mode enabled."118            )119120        ctx = self.new_context(dict(*args, **kwargs))121122        try:123            return self.environment_class.concat(  # type: ignore124                [n async for n in self.root_render_func(ctx)]  # type: ignore125            )126        except Exception:127            return self.environment.handle_exception()128129130NativeEnvironment.template_class = NativeTemplate