For one of my sites, I need to check if several class attributes are defined and not empty. So far, I've happily used if self.attr:
, which in my mind is the shorthand for if self.attr is not None and self.attr is not '':
, or whatever the undefined value of the attribute is.
This works fine, but yields to surprising behavior when checking multiple string attributes. '' and ''
is not False
(as I expected), but ''
.
This begs the question: are there other types for which the and
operator does not force a typecast to bool
?
I can't come up with an example where this difference in behavior would cause an actual different outcome for the if
-clause (after all, ''
still evaluates to False
), but am left with the gut feeling that there's edge cases that could be a trap.
Lastly, I'd be keen to know if anybody knows why it was implemented that way? I thought the Zen of Python encourages one way and one way only, and the +
operator already seems to bethe intuitive way for string concatenation.