This is a memorandum (I was studying Click) because I saw it for the first time while studying the tutorial code.
Since the Boolean operator in Python returns the value of the comparison, not the Boolean value,
>>> def test(flag=True):
... print 'flag: %s' % (flag and 'on' or 'off')
...
If you do it
>>> test(True)
flag: on
>>> test(False)
flag: off
It looks like. Note that ʻand and ʻor
here are Boolean operators, not comparison operators.
As you can see in Python library reference, Boolean operator section, the operators ʻand,
orand
not` are evaluated in ascending order of priority as shown in the table below.
operation td> | result td> |
x or y td> | y if x is false, x td> otherwise |
x and y td> | x if x is false, y td> otherwise |
not x | True ifx is false, False td> otherwise |
Therefore, non-empty strings were always evaluated as True
, so
If flag is True
:
(Because the left term is True
)
-> 'on' or 'off'
(Because the string'on'is True
)
-> 'on'
If flag is False
:
(Because the left term is False
)
-> False or 'off'
(Because the left term is False
)
-> 'off'
It was.
It was refreshing to know what was happening. It looks refreshing and may look smart.
However, it is a different matter if I am asked if I will write like this in the future. I would honestly write this.
>>> def test(flag=True):
... print 'flag: %s' % ('on' if flag else 'off')
By the way, this is not a comprehension, it seems to be a ternary operator implemented from version 2.5, but it still looks like Python, so this is better.
Also, in the first example, there is a restriction that the part of the character string'on'must contain something that becomes True
every time. I think that it is safe to write using the ternary operator because it can be a fatal bug in some cases that the evaluation of what is assigned is restricted.
reference -Today's Python: About Boolean Operations:
Recommended Posts