Suppose you are using the value of parameter
, but if the value is say None
, then you would rather like to have an empty string ""
instead of None
. What would you do in general?
if parameter:
# use parameter (well your expression using `" " + parameter` in this case
else:
# use ""
This is what that expression is doing. First you should understand what and
and or
operator does:
a and b
returnsb
if a isTrue
, else returnsa
.a or b
returnsa
if a isTrue
, else returnsb
.
So, your expression:
parameter and (" " + parameter) or ""
which is effectively equivalent to:
(parameter and (" " + parameter)) or ""
# A1 A2 B
# A or B
How the expression is evaluated if:
-
parameter - A1
is evaluated toTrue
:result = (True and " " + parameter) or "" result = (" " + parameter) or "" result = " " + parameter
-
parameter - A1
isNone
:result = (None and " " + parameter) or "" result = None or "" result = ""
As a general suggestion, it’s better and more readable to use A if C else B
form expression for conditional expression. So, you should better use:
" " + parameter if parameter else ""
instead of the given expression. See PEP 308 – Conditional Expression for motivation behind the if-else
expression.