Skip to content
Myr

Merge pull request #1190 from pallets/native-eval

Before adoption: this commit came in with the history the project adopted, so no landing records it.

native only evals at end of render

authored by David Lord · committed by GitHub · parents f1756a3, f75cb42 · Browse files · 3 files+20 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+20 added−24 removed

  • tests:+9 added−0 removed
  • other:+11 added−24 removed

3 files+20 added−24 removed

modified:src/jinja2/nativetypes.py+7 added-24 removed
1import types1from ast import literal_eval2from itertools import chain3from itertools import islice4
4 unmodified lines
9from .environment import Environment10from .environment import Template111214def native_concat(nodes, preserve_quotes=True):13def native_concat(nodes):14 """Return a native Python type from the list of compiled nodes. If15 the result is a single node, its value is returned. Otherwise, the16 nodes are concatenated as strings. If the result can be parsed with17 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,18 the string is returned.1920 :param nodes: Iterable of nodes to concatenate.22 :param preserve_quotes: Whether to re-wrap literal strings with23 quotes, to preserve quotes around expressions for later parsing.24 Should be ``False`` in :meth:`NativeEnvironment.render`.21 """22 head = list(islice(nodes, 2))2324 if not head:
1 unmodified line
2627 if len(head) == 1:28 raw = head[0]29 else:34 if isinstance(nodes, types.GeneratorType):35 nodes = chain(head, nodes)36 raw = u"".join([text_type(v) for v in nodes])30 raw = u"".join([text_type(v) for v in chain(head, nodes)])3132 try:39 literal = literal_eval(raw)33 return literal_eval(raw)34 except (ValueError, SyntaxError, MemoryError):35 return raw3643 # If literal_eval returned a string, re-wrap with the original44 # quote character to avoid dropping quotes between expression nodes.45 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46 # be ('a', 'b').47 if preserve_quotes and isinstance(literal, str):48 return "{quote}{}{quote}".format(literal, quote=raw[0])3750 return literal515238class NativeCodeGenerator(CodeGenerator):39 """A code generator which renders Python types by not adding55 ``to_string()`` around output nodes, and using :func:`native_concat`56 to convert complex strings back to Python types if possible.40 ``to_string()`` around output nodes.41 """4243 @staticmethod44 def _default_finalize(value):45 return value4647 def _output_const_repr(self, group):64 return repr(native_concat(group))48 return repr(u"".join([text_type(v) for v in group]))4950 def _output_child_to_const(self, node, frame, finalize):51 const = node.as_const(frame.eval_ctx)52
30 unmodified lines
83 with :func:`ast.literal_eval`, the parsed value is returned.84 Otherwise, the string is returned.85 """86 vars = dict(*args, **kwargs)8788 try:104 return native_concat(105 self.root_render_func(self.new_context(vars)), preserve_quotes=False106 )89 return native_concat(self.root_render_func(self.new_context(vars)))90 except Exception:91 return self.environment.handle_exception()9293
1 unmodified line
modified:tests/test_nativetypes.py+9 added
132 unmodified lines
133 result = t.render(host="localhost", user="Jinja")134 assert result == "--host='localhost' --user \"Jinja\""135136137def test_no_intermediate_eval(env):138 t = env.from_string("0.000{{ a }}")139 result = t.render(a=7)140 assert isinstance(result, float)141 # If intermediate eval happened, 0.000 would render 0.0, then 7142 # would be appended, resulting in 0.07.143 assert result < 0.007 # TODO use math.isclose in Python 3144145146def test_spontaneous_env():147 t = NativeTemplate("{{ true }}")148 assert isinstance(t.environment, NativeEnvironment)
modified:CHANGES.rst+4 added
25 unmodified lines
26- The special ``namespace()`` assignment object in templates works in27 async environments. :issue:`1180`28- Fix whitespace being removed before tags in the middle of lines when29 ``lstrip_blocks`` is enabled. :issue:`1138`30- :class:`~nativetypes.NativeEnvironment` doesn't evaluate31 intermediate strings during rendering. This prevents early32 evaluation which could change the value of an expression.33 :issue:`1186`343536Version 2.11.137--------------
737 unmodified lines