Skip to content

Commit

Permalink
Merge pull request #1537 from mkrizek/literal_eval-py-310
Browse files Browse the repository at this point in the history
native: keep same behavior on Python 3.10
  • Loading branch information
davidism committed Nov 9, 2021
2 parents a4e2532 + bb0db82 commit 99b6fc7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.rst
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion src/jinja2/nativetypes.py
@@ -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

Expand Down Expand Up @@ -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

Expand Down
6 changes: 6 additions & 0 deletions tests/test_nativetypes.py
Expand Up @@ -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"

0 comments on commit 99b6fc7

Please sign in to comment.