DEV Community

icncsx
icncsx

Posted on

What determines the truthiness of an object in Python?

In Python we have truthy and falsy values. For example 0 is falsy and all other numbers are truthy. In fact, all objects in Python have a truth value.

By default, all objects are considered to be truthy.

class Foo:
    pass

bool(Foo()) # True
Enter fullscreen mode Exit fullscreen mode

If you want to override this default behaviour, you have to implement the __bool__ method. If an object defines __bool__, then Python calls that method to determine its truthiness.

class Bar:
    def __bool__(self):
        return False

bool(Bar()) # False
Enter fullscreen mode Exit fullscreen mode

Now all instances of Bar are False.

Top comments (4)

Collapse
 
seanthegreat profile image
Sean Antony Brunton

Truthy and Falsiness in Clojure seems more simple than doing that. What's makes this concept so powerful is that it "wants" to be nil or a nullset value. Only thing stopping that is if something which is "true" is in its way. So in essence we can have Booleans acting in "Truthiness" and visa versa in one kind of literal presentation of a data structure . Don't have use any kind of other function to distinguish wether something is "treated" as truth as opposed to it being objectively true. When something wants to evaluate to nullset or nil, we can "find" mathematical closure far more efficiently, well it's the way I see right now LoL. Still Python is awesome to use for data science and mucking about with Jupyter Notebooks... Anyway my two cents worth there 😆 HaPPy HaCkiNg!

Collapse
 
paddy3118 profile image
Paddy3118

It is pythonic to expect empty collections to be False. Empty built in collections such as lists, strings, tuples, dicts, sets, etc are all False.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Truth be hold, Python is as cool as always because of magic methods. (Another cool is Jupyter Notebook magic methods.)

Collapse
 
kmistele profile image
Kyle Mistele

Really cool, didn’t know you could do that!