2

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 ?

basic mojo
  • 128
  • 2
  • 12

3 Answers3

8

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
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • 1
    Just to add some additional info from [basic customization](https://docs.python.org/3/reference/datamodel.html#object.__bool__) **object.__bool__(self)**: Called to implement truth value testing and the built-in operation `bool()`; should return `False` or `True`. When this method is not defined, `__len__()` is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither `__len__()` nor `__bool__()`, all its instances are considered true. – buran Jan 07 '21 at 14:51
  • @buran Thanks, I always forget about that. It's such an odd decision . Why not just write a `__bool__` and have it check `len` if you want it decided by the length? It seems weird to hard code that into the language. – Carcigenicate Jan 07 '21 at 14:55
  • Thanks for the quick reply, but the question has already been marked as duplicate, I couldn't get the correct terms to search for, that might be the issue. But thanks – basic mojo Jan 07 '21 at 14:57
0

Good question! This is not to do with the if statement. Instead, it is the object itself.

If an object defines the builtin method __bool__, it can decide whether it is "truthy" or "falsey" (aka whether to return true or false).

See this answer for more details, or the official Python docs


Here is a quick example of a Dog class which is False if it has no name:

class Dog:
    def __init__(self, name):
        this.name = name

    def __bool__(self):
        return this.name != ""

dog1 = Dog("")
dog2 = Dog("Foo")
if (dog1): print("dog1")
if (dog2): print("dog2")
> dog2
dwb
  • 2,136
  • 13
  • 27
-1

In Python, booleans (result of an if-else condition) is often interpreted as integers 0 and 1. 0 being False and 1 being True.

In you case since, you assigned value of a to be 0, which python interpreted as False, hence it didn't print anything.

A simple rule in Python is and empty container (list, dict, set, tuple, str) or None or Number (int/float) which is 0 would be considered as False. Any number greater than 0 or 0.0000 so on would be considered True.

XAMES3
  • 147
  • 1
  • 6