Python / Core Python Fundamentals Interview Questions
How does Python determine whether a custom object is truthy or falsy?
Every Python object has a boolean value. In a boolean context (an if condition, a while condition, or passed to bool()), Python calls the object's __bool__ method first. If that is not defined, it falls back to __len__ and returns False if __len__ returns 0. If neither is defined, the object is always truthy.
class Queue: def __init__(self): self._data = [] def enqueue(self, item): self._data.append(item) def __len__(self): return len(self._data) def __bool__(self): return len(self._data) > 0 # explicit q = Queue() if not q: print('Queue is empty') # printed â __bool__ returns False q.enqueue('item') if q: print('Queue has items') # printed â __bool__ returns True
The built-in falsy values to memorise: None, False, 0, 0.0, 0j (complex zero), '' (empty string), b'' (empty bytes), [], (), {}, set(), and any object whose __bool__ returns False or whose __len__ returns 0.
Practical impact: you can write Pythonic guards like if items:, while queue:, and return value or default instead of verbose length checks. The short-circuit operators and and or return one of their operands, not necessarily a bool: 'alice' or 'default' returns 'alice'; '' or 'default' returns 'default'.
More Related questions...