Search code examples
pythonpython-3.xpython-2.x

Digging deeper into python if statements


It might be a really silly question, but I was not able to find the answer to it anywhere else, I've looked at SO, but there is nothing I could find related to my question.

Question:

In python, don't know about other languages, whenever we call if statements for a builtin class it returns something which the if statement interprets, For example,

a = 0
if a: print("Hello World")

The above statement does not print anything as the if a is False. Now which method returned that it is False, or is there a method the if statement calls in order to know it ??

Or more precisely, how does the if statement work in python in a deeper level ?


Solution

  • Objects have __bool__ methods that are called when an object needs to be treated as a boolean value. You can see that with a simple test:

    class Test:
        def __bool__(self):
            print("Bool called")
            return False
    
    t = Test()
    if t:   # Prints "Bool Called"
        pass
    

    bool(0) gives False, so 0 is considered to be a "falsey" value.

    A class can also be considered to be truthy or falsey based on it's reported length as well:

    class Test:
        def __len__(self):
            print("Len called")
            return 0
    
    t = Test()
    if t:
        pass