bool in Python
Introduction
bool inherits from
int
https://github.com/python/cpython/blob/main/Doc/c-api/bool.rst
Most values are True
Almost any value evaluates to True if it has any content.
Any string is True except empty strings.
Any number is True except 0.
Any list, tuple, set and dictionary is True except empty ones.
print(bool("testsetup.ru")) print(bool(1961)) print(bool(-273)) print(bool(["cordoba", "fuengirola", "malaga"]))
True True True True
Some values are False
There are not many values that evaluate to false, apart from empty values such as (), [], {}, "", the number 0
and the value None.
And, of course, the value False evaluates to false.
print(bool(False)) print(bool(None)) print(bool(0)) print(bool("")) print(bool(())) print(bool([])) print(bool({}))
False False False False False False False
if X vs if X is True
Later we will need the understanding of the difference between if X and if X is True
if X is True - this is a stricter condition.
url = "testsetup.ru" if url: print('if url') if url is True: print('if url is True!')
if url
url is not an empty string, so if url executes as True.
But url is not True. The type of url is
str
If url is made an empty string, neither condition will execute.
url = "" if url: print('if url') if url is True: print('if url is True!')
If the variable is explicitly set to True, or the value comes from a function that returns True, both conditions will execute.
verified = True if verified: print('if verified') if verified is True: print('if verified is True!')
if verified if verified is True!
Explicitly set bool for your own object
Let us apply bool() to objects of a class that has no custom methods except __init__()
class My: def __init__(self, length: int) -> None: self.length = length if __name__ == '__main__': print(bool(My(0))) # True print(bool(My(1))) # True # print(bool(My("a"))) # TypeError: '>' not supported between instances of 'str' and 'int'
True
True
Since an empty object of a user class does not fall into the group of objects that are considered False we got True both times
To explicitly set the desired behaviour we use the magic method __bool__()
class My: def __init__(self, length: int) -> None: self.length = length def __bool__(self) -> bool: return True if self.length > 0 else False if __name__ == '__main__': print(bool(My(0))) # False print(bool(My(1))) # True print(bool(My(-1))) # False
False True False
Note that the opposite logic can also be used. It will be intuitively unclear, but formally nobody forbids doing so.
class My: def __init__(self, length: int) -> None: self.length = length def __bool__(self) -> bool: return True if self.length <= 0 else False if __name__ == '__main__': print(bool(My(0))) # True print(bool(My(1))) # False
True
False
From __bool__() you can only return bool
class My: def __init__(self, length: int) -> None: self.length = length def __bool__(self) -> bool: return 0 if __name__ == '__main__': print(bool(My(0))) # False
TypeError: __bool__ should return bool, returned int
The second magic method that can be used for the same purpose is __len__()
class My: def __init__(self, length: int) -> None: self.length = length def __len__(self) -> int: return self.length if __name__ == '__main__': print(bool(My(0))) # False print(bool(My(1))) # True print(bool(My(-1))) # ValueError: __len__() should return >= 0
False True
The method is not identical to the previous one , for example, negative numbers can no longer be passed to My().
ValueError: __len__() should return >= 0
__len__() must return int
class My: def __init__(self, length: int) -> None: self.length = length def __len__(self) -> int: return "heihei.ru" # TypeError: 'str' object cannot be interpreted as an integer if __name__ == '__main__': print(bool(My(0))) # False
TypeError: 'str' object cannot be interpreted as an integer
Comparison with bool
Let us recall the chapter
if X vs if X is True
An example of comparison with True that will execute as True
class My: def __bool__(self) -> bool: print('__bool__ called') return True my = My() if my: print('Done!')
__bool__ called Done!
And the following example will not execute as True, because there it is explicitly checked whether my is the constant True.
my is an object of the class My, so it will not even reach the call of the method __bool__() .
class My: def __bool__(self) -> bool: print('__bool__ called') return True my = My() if my is True: print('Done!')
A way that is recommended to avoid, because == calls the method __eq__() and not __bool__() so the result may be
unpredictable.
For example, if you add to
this example
the method __eq__(), which always returns True, we get a completely different result
class My: def __init__(self, length: int) -> None: self.length = length def __bool__(self) -> bool: print('__bool__ called') return True if self.length > 0 else False def __eq__(self, other: object) -> bool: print('__eq__ called') return True my = My(0) if my == True: print('Done!') my = My(-1) if my == True: print('Done!')
__eq__ called Done! __eq__ called Done!
Both times the comparison worked as True, although the length is less than or equal to zero.
Method Resulution Order
# builtins.py Python 3.12.2 # … class bool(int): """ bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed. """ def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __init__(self, x): # real signature unknown; restored from __doc__ pass def __invert__(self, *args, **kwargs): # real signature unknown """ ~self """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass
print(bool.__mro__)
(<class 'bool'>, <class 'int'>, <class 'object'>)
print(True * 5)
5
print(True + True + 2)
4
print(1 / False)
Traceback (most recent call last):
File "C:\python\main.py", line 21, in
Video
One of the important sources of information for writing the article is a video from the course "The Best Python Course"
Article author: Andrei Olegovich