]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
native: keep same behavior on Python 3.10 1537/head
authorMartin Krizek <martin.krizek@gmail.com>
Tue, 9 Nov 2021 16:15:31 +0000 (17:15 +0100)
committerDavid Lord <davidism@gmail.com>
Tue, 9 Nov 2021 16:41:02 +0000 (08:41 -0800)
CHANGES.rst
src/jinja2/nativetypes.py
tests/test_nativetypes.py

index de9bd455819bdde20672eb3e5dd879a6f67182a9..e859ab3fa7b84811cedffb8f29d4b786b024ead4 100644 (file)
@@ -7,6 +7,8 @@ Unreleased
 
 -   Fix traceback rewriting internals for Python 3.10 and 3.11.
     :issue:`1535`
+-   Fix how the native environment treats leading and trailing spaces
+    when parsing values on Python 3.10. :pr:`1537`
 
 
 Version 3.0.2
index 88eeecc497f4a1021052a14fcb24d88241e98a11..20597d50ab910a7b7e1f9365bb441a9e10a6f71a 100644 (file)
@@ -1,5 +1,6 @@
 import typing as t
 from ast import literal_eval
+from ast import parse
 from itertools import chain
 from itertools import islice
 
@@ -33,7 +34,12 @@ def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:
         raw = "".join([str(v) for v in chain(head, values)])
 
     try:
-        return literal_eval(raw)
+        return literal_eval(
+            # In Python 3.10+ ast.literal_eval removes leading spaces/tabs
+            # from the given string. For backwards compatibility we need to
+            # parse the string ourselves without removing leading spaces/tabs.
+            parse(raw, mode="eval")
+        )
     except (ValueError, SyntaxError, MemoryError):
         return raw
 
index 22581813c009fab66e37a3f50996bc17b9289138..9bae938cdb3438a98fe8c000d153cc3f766d0dbc 100644 (file)
@@ -147,3 +147,9 @@ def test_no_intermediate_eval(env):
 def test_spontaneous_env():
     t = NativeTemplate("{{ true }}")
     assert isinstance(t.environment, NativeEnvironment)
+
+
+def test_leading_spaces(env):
+    t = env.from_string(" {{ True }}")
+    result = t.render()
+    assert result == " True"