jinja icon indicating copy to clipboard operation
jinja copied to clipboard

explain associativity and precedence between operators

Open ssato opened this issue 3 years ago • 2 comments

The doc of jinja lacks of descriptions about the followings, if I'm not mistaken.

  • associative properties of operators
  • precedence between operators

Therefore, there are some cases users may not be able to expect how expressions will be evaluated beforehand, like the following examples, IMHO.

  • 1 + 2 * 3
  • 1 + "2" | int
  • xs | length > 0 (where xs is a list, e.g. [1, 2])
  • xs | length > 0 is true

To resolve this, I would like to suggest to enhance the doc (the section "Template Designer Documentation" should be suitable for this purpose, I think), to add some notes or a section to explain about associativity of, and precedence between operators like the followings.

  • Operators are left associative basically, that is, grouped from left to right. For example,
    • {{ 1 + 2 - 3 }} will be evaluated as {{ (1 + 2) - 3 }}
    • {{ 3 ** 2 ** 3 }} will be evaluated as {{ (3 ** 2) ** 3 }} unlike python evaluates it as {{ 3 ** (2 ** 3) }}
    • {{ xs | list | length }} will be evaluated as {{ (xs | list) | length }}
  • Operators have precedence if similar named functions exist in python. For example,
    • {{ 1 + 2 * 3 }} will be evaluated as {{ 1 + (2 * 3) }} and return 7
  • Some operators may have higher priority than other operators. For example,
    • {{ 1 + "2" | int }} will be evaluated as {{ 1 + ("2" | int) }} and return 3
    • {{ [3] + [2, 1] | sort }} will be evaluated to {{ [3] + ([2, 1] | sort) }} and return [3, 1, 2]
  • Precedence between operators are ... (explanation) ...

BTW, this is related to #379 and may close it.

ssato avatar Nov 07 '22 16:11 ssato

Excuse me. I made a mistake that filters are always applied with '|' operator, AFAIK. So that it may be enough to add notes about associativity and precedence between operators.

ssato avatar Nov 07 '22 16:11 ssato

To avoid unnecessary confusion, I update the title and description of this issue.

ssato avatar Nov 07 '22 16:11 ssato