Interview frequency: …
Short answer
An object is falsy if it defines __bool__ returning False or __len__ returning zero; the built-in falsy values are None, False, 0, 0.0, the empty string and empty collections. Everything else is truthy.
Explanation
This lets you write if items: instead of if len(items) > 0. Be careful, though, when 0 or an empty string is a valid value: if not quantity treats a quantity of zero as if it were missing. In that case test for None explicitly. When defining a class, define __bool__ only when truthiness has a clear meaning.
Code example
def apply_discount(price, discount=None):
if discount is None: # And not: if not discount
return price
return price - discount # discount=0 Valid value
class Cart:
def __init__(self):
self.items = []
def __len__(self):
return len(self.items) # Empty basket falsyCommon mistakes
- Using if not value to check for None, which also rejects valid values such as 0 and "".
- Comparing lists with == [] instead of relying on truthiness.