I just learned there are truthy and falsy values in python which are different from the normal True
and False
.
Python determines the truthiness by applying bool()
to the type, which returns True
or False
which is used in an expression like if
or while
.
Here is an example for a custom class Vector2d
and it's instance returning False
when the magnitude (lenght of a vector) is 0, otherwise True
.
import math
class Vector2d(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
a = Vector2d(0,0)
print(bool(a)) #False
b = Vector2d(10,0)
print(bool(b)) #True
Note: If we wouldn't have defined __bool__
it would always return True, as instances of a user-defined class are considered truthy by default.
Example from the book: "Fluent in Python, clear, concise and effective programming"