Add an optional chaining operator
mitsuhiko opened this issue · comments
Cross posting this as it was opened against MiniJinja: mitsuhiko/minijinja#215
The proposal was made to add a ?.
operator which would work like .
but does not error if the left side is already undefined or potentially also None
. This would permit something like this:
{% if first_undefined?.attribute?.nested %}...{% endif %}
That's what ChainableUndefined
does, without any syntax changes. It was added in Jinja 2.11.0, see issue #977 and PR #997.
I think the idea is to be more explicit and not globally enabling all undefineds to be chainable but only those where you want it because you expect a key/attr to not exist
I'm not comfortable adding more changes to the language right now, especially when it's already available as an undefined class. Jinja as a language isn't formally defined, and the lexer/parser/compiler is really complicated already. It's already hard enough for me to reason about the existing behaviors when maintaining the code or triaging issues for the existing grammar. That's something I want to address first.
See #1194. I'm pretty sure I mentioned this when discussing MiniJinja before, since it was an opportunity to document what the grammar was, but that didn't go anywhere.
The suggestion made in the linked issue was {% if object.prop and object.prop.subprop >= 1 %}
, which is essentially what ChainableUndefined
does, so I'm going to close this for now.
I learned over the years that swapping out the Undefined
really does not work all that well because you kinda want to rely on the runtime semantics. I guess though that the appetite of adding new explicit operators is not very high.