pallets/jinja

float comparison with x.10 fails

brianjmurrell opened this issue · 3 comments

$ cat template
# VERSION: {{ VERSION }}
# {{ (VERSION|float < 8.9) }}
# {{ (VERSION|float < 8.10) }}
$ jinja2 -D VERSION=8.8 --format=json template
# VERSION: 8.8
# True
# False

That False should be True given that 8.8 is < 8.10.

Environment:

  • Python version: 3.12.3
  • Jinja version: 3.1.3

The float 8.10 is equivalent to 8.1, trailing zeros don't matter. 8.8 is less then 8.9, which is less than 8.99, which is less than 9. I'm fairly sure that's universally true in programming languages. You're looking for version parsing and comparison, which is completely different. Try https://packaging.pypa.io/en/stable/version.html

Ah, yes. The distinction between true floats and version specifiers.

Try https://packaging.pypa.io/en/stable/version.html

How can that be used in the context of Jinja templates though. As in doing version comparison with template variables, etc.

There are plenty of ways to customize the Jinja environment. You could define a filter that uses it, for example value|version_lt(other), or a test value is version_lt(other), or inject a global function like version_lt(value, other). All that said, typically you should do complex processing in the Python code before the render.