Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug with right-left associativity of exponent #1722

Open
krepysh opened this issue Sep 19, 2022 · 2 comments
Open

Bug with right-left associativity of exponent #1722

krepysh opened this issue Sep 19, 2022 · 2 comments
Milestone

Comments

@krepysh
Copy link
Contributor

krepysh commented Sep 19, 2022

Discovered it when working on #1720. Looks like the fix will fix both issues.

Minimal reproducible example

from jinja2 import Environment
env = Environment()
tmpl = env.from_string('{{ 2 ** 3 ** 2 }}')
assert eval('2 ** 3 ** 2') == 512 
assert tmpl.render() == '512' # it's actualy 64 because of wrong order

Expected behaviour

I expected exact behaviour as in pure python. We need to start evaluation from left to right.

Environment:

  • Python version: 3.9.12
  • Jinja version: 3.1.x
@mkrizek
Copy link
Contributor

mkrizek commented Sep 19, 2022

Not sure "bug" is the correct word here, it is documented behavior, from https://jinja.palletsprojects.com/en/3.1.x/templates/#math:

Unlike Python, chained pow is evaluated left to right. {{ 333 }} is evaluated as (33)3 in Jinja, but would be evaluated as 3(33) in Python. Use parentheses in Jinja to be explicit about what order you want. It is usually preferable to do extended math in Python and pass the results to render rather than doing it in the template.

However the docs also state:

This behavior may be changed in the future to match Python, if it’s possible to introduce an upgrade path.

@davidism davidism added this to the 3.2.0 milestone Sep 19, 2022
@davidism
Copy link
Member

davidism commented Sep 19, 2022

We should have done it years ago, the longer you wait the more potential there is for someone relying on it. This has come up a few times before, and we've always decided to leave it as-is.

But I have a feeling the only people using ** in templates are doing math, and expect it to work the right way, report it here and it gets closed. So I'm going to change sides and say let's fix it in the next feature release 3.2. Operator precedence should be the same as Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants