Recently I have stumbled across an interesting piece of code in Python
condition and 'string1' or 'string2'
It took me some time to figure out its meaning but in the end it is another way to write a ternary expression
'string1' if condition else 'string2'
This made me realise x or y
does not return True or False but x if x is True and y otherwise (Python Docs).
However, I don't see the reason why Python was designed that way. I've seen some use cases in checking for None
y = None
x = y or default
but this can be easily and clearer achieved using the following
x = y if y else default
Runtime-wise I also don't see the benefit since, if x is False, the second term in x or y
needs to be evaluated at some point.
And in terms of code readability I would expect bool_test = x or y
to contain a Boolean value.
So overall, why was Python designed in that way?