-
Does this have any other names besides short-circuit evaluation? show_warning = False
warning = t'<div class="alert">Warning message</div>'
page = html(t"<main>{show_warning and warning}</main>")
# <main></main> It seems to involve more than the traditional meaning of that term. From playing around, it seems like the rightmost >>> show_warning = t'<b>False</b>'
... warning = t'<div class="alert">Warning message</div>'
... page = html(t"<main>{show_warning and show_warning and warning}</main>")
... print(page)
...
<main><div class="alert">Warning message</div></main>
>>> show_warning = t'<b>False</b>'
... page = html(t"<main>{show_warning and show_warning}</main>")
... print(page)
...
<main><b>False</b></main>
>>> show_warning = 'omg'
... page = html(t"<main>{show_warning and show_warning}</main>")
... print(page)
...
<main>omg</main> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Not that I'm aware of! There's no magic in this syntax: since you're inside curly braces, it's just Python. Python has short circuit boolean operators. In addition to handling boolean values (
A few examples that just use Python, not >>> False and "hello"
False
>>> True and "hello"
"hello"
>>> "" and "hello" # "" is considered false-y
""
>>> "fun" and "hello" # "fun" is truth-y
"hello"
>>> "fun" and "hello" and "cool"
"cool"
>>> "fun" and 0 and "cool"
0 Likewise, >>> False or "hello"
"hello"
>>> True or "hello"
True
>>> False or ""
"" |
Beta Was this translation helpful? Give feedback.
Not that I'm aware of!
There's no magic in this syntax: since you're inside curly braces, it's just Python. Python has short circuit boolean operators. In addition to handling boolean values (
True
andFalse
), they handle "truth-y" values (non-empty strings, non-zero integers, and anything else for whichbool(value)
isTrue
) and "false-y" values (empty strings,0
, anything for whichbool(value)
isFalse
).and
evaluates each value in turn. If one of them is false-y,and
returns it right away (that's the short circuit). Otherwise,and
returns the last evaluated value, which will be on the right.A few examples that just use P…