Unpythonic operator precedence #119

Open
luc-j-bourhis opened this Issue Apr 25, 2012 · 4 comments

4 participants

@luc-j-bourhis

Jinja2 version 2.6 parses {{ a * b % c }} as a * (b %c) whereas Python would parse it as (a * b) % c.
Here is a regression test:

#############################################################
from jinja2 import Environment

env = Environment()
t = env.from_string('''
{{2 * 4 % 8}}
{{2 * 12 % 8}}
''')
rendered = t.render()
correct = '''
0
0
'''
assert rendered == correct, "%s\ninstead of%s" % (rendered, correct)
#############################################################

fails with

AssertionError:
8
8
instead of
0
0

@luc-j-bourhis

Reading through jinja2.parser, if I understand correctly, the precedences of operators *, /, // and % does not follow Python: in jinja2, they are strictly in that order, from lowest to highest precedence, whereas in Python they all have the same precedence. This does not matter for * and / as they commute (baring floating-point round-off) but it does matter for // and %. Which means that expression involving // are "wrong" as well: 2 * 6 // 12 = 0 as per jinja2 but = 1 as per Python.

@mitsuhiko
The Pallets Projects member

Yeah, I wanted to fix this a long time ago but I'm afraid of breaking templates that rely on that by accident :(

@jeffwidman jeffwidman added this to the 3.0 milestone Apr 12, 2016
@ngaya-ll

Maybe this could be configurable? That way it wouldn't break backward compatibility, but the old precedence could be deprecated and eventually removed completely.

@jeffwidman
The Pallets Projects member

That sounds reasonable to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment