Things That Are Falsy In Python
Python has a neat and simple truthy and falsy concept. This can make your programs more readable, easier to maintain and avoid logical errors. In general, truthiness in Python is about values that are not zero or non empty.
What is truthy and falsy values?
Truthy values are values that are considered to evaluate to True
in a boolean context. In a similar way Falsy values are values that are considered to be False
in a boolean context.
For example, the value 0 in Python is considered Falsy while 1 is considered Truthy.
In [1]: 0 == True
Out[1]: False
In [2]: 1 == True
Out[2]: True
All other numbers are evaluate to a Truthy value.
Truth value testing
Python documentation clearly states that we can distinguish the Truthy and Falsy values in 4 main categories.
- Objects
- Constants
- Zero of any numeric built in type
- empty collections or sequences.
Objects
Objects evaluate to True
except if they define either the __bool__()
or the __len__()
method. Therefore, if you want your custom objects to evaluate to anything else other that True
you can overwrite these two methods based on your business logic.
class MyClass:
x = 1
my_object = MyClass()
if my_object:
print('True')
else:
print('False')
# result
True
After overwriting the __len__()
method we can see that the result of the if statement is different.
class MyClass:
x = 1
def __len__(self):
return 0
my_object = MyClass()
if my_object:
print('True')
else:
print('False')
# result
False
Constants
If a constant is defined as either None
or False
will evaluate to a Falsy value.
Numeric Types
All the 0 numeric types such as int, float, complex, Decimal and Fraction are evaluate to a Falsy value. For example all the values below are all false.
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
Empty collections or sequences
All the built in empty sequences or collections are evaluate to a False
value.
For example, ''
, ()
, []
, {}
, set()
, range(0)
are all false.
Summary
- Truthy values are values that are
True
in a boolean context. - Falsy values are values are
False
in a boolean context. - Python documentation states that there are 4 main categories of Falsy and Truthy items.
- If used correctly they can improve the readability and maintainability of your codebase.