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

Type safe equality check #727

Open
wolfv opened this issue Feb 18, 2025 · 3 comments
Open

Type safe equality check #727

wolfv opened this issue Feb 18, 2025 · 3 comments

Comments

@wolfv
Copy link
Contributor

wolfv commented Feb 18, 2025

I was wondering if there is already support for type safe equality.

I think:

{{ item.href == "/index" }}  # works fine
{{ item.href == 5 }} # always false
{{ item.href is 5 }} # syntax error: unexpected integer, expected identifier
{{ item.href === 5 }} # doesn't exist

IMO it could be a helpful feature to have a variant of == (or == itself, toggled by a setting) behave in a "type-safe" way and throw an error if someone attempts to compare different types.

I think this operator could be is, or it could be ===. But maybe there are other good ideas.

@mitsuhiko
Copy link
Owner

This might be somewhat related to #721. I don't want to add custom operators but if there are more use cases for changing how these things work, one could consider replacing them with custom callbacks.

That said, I'm not convinced it's a good idea to have comparison operators panic on type mismatches. There are not that many distinct types floating around in the engine and some coercion needs to take place. For instance you would not want an error if you do undefined == 42 or 42.0 == 42.

Custom operator would mean that Jinja2 also needs that, otherwise we end up in the situation where the engines diverge which I want to mostly avoid. However Jinja2 does allow overriding the operator callback functions.

@wolfv
Copy link
Contributor Author

wolfv commented Feb 18, 2025

Would you be open to adding this as a setting to the syntax options? Could be opt-in to make == error (e.g. when comparing between string and integer).

@mitsuhiko
Copy link
Owner

I'm not sure what the right course of action is at the moment.

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

2 participants