pallets / jinja

A very fast and expressive template engine.
https://jinja.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
10.12k stars 1.6k forks source link

float comparison with x.10 fails #1989

Closed brianjmurrell closed 1 month ago

brianjmurrell commented 1 month ago
$ 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:

davidism commented 1 month ago

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

brianjmurrell commented 1 month ago

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.

davidism commented 1 month ago

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.