Для контекста, я делаю несколько тестов, чтобы увидеть, установлено ли только одно из двух значений - мне нужно, чтобы пользователь указал одно, но не оба или ни то, ни другое.Питонический способ сделать это будет bool(string1) != bool(string2)
.Есть несколько способов проверить это в jinja, которые должны быть эквивалентны, но это не так.
from jinja2 import Environment
expr = Environment().compile_expression
ctx = dict(foo="baz", bar="")
# Recreating `bool(string)` behaves as you expect.
expr("(foo | length) != 0")(ctx) # True
expr("(bar | length) != 0")(ctx) # False
# Comparing them, however...
expr("((foo | length) != 0) != ((bar | length) != 0)")(ctx) # False
# Huh? Do I not remember how boolean logic works?
expr("foo != bar")(foo=True, bar=False) # True
# Let's try another syntax, which should be equivalent:
expr("((foo | length) != 0) is not eq((bar | length) != 0)")(ctx) # True
# Strange. Let's also try the ruby/js style of casting to a boolean:
expr("(not not foo) != (not not bar)")(ctx) # True
# And just out of curiosity, what if we applied the non-operator way to the length tests themselves?
expr("((foo | length) is not eq(0)) != ((bar | length) is not eq(0))")(ctx) # True
Почему использование оператора равенства не всегда работает должным образом с логическими значениями?