Python 3D Academyবাংলা

__call__ and __bool__: objects you can call, and objects that are true or false

🌍 In real life. A coffee machine set to "large, no sugar" needs only one button: press it and it uses its own settings. And a wallet is either empty or not, which is all you need to know before you go shopping.

The idea in one sentence: __call__ lets you call an object like a function, obj(x), using the settings in its fields; __bool__ decides whether the object counts as True or False in if, while and bool().

Its words:

  • callable: anything you can put brackets after: functions, classes, and objects with __call__; callable(x) asks
  • truthiness: whether a value counts as True (Lesson 5.4): 0, "" and [] count as False
  • the fallback: without __bool__, Python asks __len__ and treats 0 as False; with neither, every object is True

Step by step:

  1. vat = Tax(15) stores the rate in the object
  2. vat(200) makes Python run vat.__call__(200), which uses self.rate
  3. bool(vat) (and if vat:) makes Python run vat.__bool__()

Watch each line become its dunder call:

Where bool() looks when there is no __bool__. A class that holds things usually has a __len__ (Lesson 24.3), and an empty container should count as False, just like an empty list. So Python falls back to __len__: 0 means False. Here Bag has only a __len__, and its bag is empty:

class Tax:
    def __init__(self, rate):
        self.rate = rate                    # percent

    def __call__(self, amount):
        return amount + amount * self.rate // 100

vat = Tax(15)
print(vat(200), vat(1000))
print(callable(vat), callable(5))

class Cart:
    def __init__(self):
        self.items = []

    def __len__(self):
        return len(self.items)

cart = Cart()
print("empty" if not cart else "has items")
cart.items.append("rice")
print("empty" if not cart else "has items")

A callable object or a closure? Tax(15) and make_multiplier(3) from Lesson 16.5 do the same job: a function that remembers a setting. Use a closure for one small setting; use a class with __call__ when you also want to read or change the settings (vat.rate = 18), give it other methods, or print it nicely with __repr__.

Mistakes and edge cases.

  • __bool__ must give back True or False: returning a number, even 0 or 1, is a TypeError ("bool should return bool")
  • calling an object without __call__: a TypeError ("'Bag' object is not callable"), as the animation showed
  • if obj: vs if obj is not None:: with a __len__ or __bool__, an empty but real object counts as False; to ask only "is there an object?", compare with None
  • __call__ is looked up on the class: giving one object its own obj.__call__ = … doesn't make it callable

Why give objects these powers? They let your objects slot into code written for functions or for True/False tests: a callable Tax can be passed anywhere a function is expected (like map(vat, prices)), and if cart: reads naturally once an empty cart counts as False.

Quiz

  1. What does this print?

    class Tax:
        def __init__(self, rate):
            self.rate = rate                    # percent
    
        def __call__(self, amount):
            return amount + amount * self.rate // 100
    
    t = Tax(10)
    print(t(50), t(100))
  2. What does this print?

    class Queue:
        def __init__(self):
            self.people = []
    
        def __len__(self):
            return len(self.people)
    
    q = Queue()
    print(bool(q))
    q.people.append("Ana")
    print(bool(q))
  3. What does this print?

    class Box:
        pass
    
    print(bool(Box()), callable(Box), callable(Box()))
  4. Which __bool__ is correct for a Wallet with self.taka?

    • return self.taka > 0
    • return self.taka
    • print(self.taka > 0)
  5. A Greeter is meant to be called like a function, as the last line does, but greeter("Ana") stops with "'Greeter' object is not callable". Which line is wrong?

    class Greeter:
        def __init__(self, word):
            self.word = word
    
        def call(self, name):
            return self.word + ", " + name
    
    greeter = Greeter("Hi")
    print(greeter("Ana"))

Coding tasks

  1. Write class Tax(rate): calling a Tax object with an amount returns the amount plus rate percent of it, worked out as amount + amount * rate // 100.

  2. Write class Wallet(taka) so that a wallet counts as True only when it holds more than 0 taka, in bool(), if and while.