Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean context of a python object [duplicate]

Can I use a python object in a desired boolean context? By default any object is True in boolean context.

>>> class Person():
...           pass
... 
>>> a=Person()
>>> bool(a)
True

Like bool(0) returns False and bool(1) returns True.Can i have any way to define an object to have it's boolean value either True or False. Correct me if i'm wrong anywhere,thanks.

like image 883
darxtrix Avatar asked Jan 24 '14 12:01

darxtrix


2 Answers

class Something(object):
    def __nonzero__(self):
        return False  # Something is False always. 

print bool(Something())

Take note __nonzero__ has been renamed to __bool__ in Python 3.x

As pointed out in a comment, you would be better to define __len__ on container like collections. When __len__ returns 0, bool(x) will evaluate False. Otherwise any positive number above 1 will equate to True.

like image 73
Jakob Bowyer Avatar answered Sep 30 '22 04:09

Jakob Bowyer


See the documentation on Truth Value Testing. It first checks if your instance has a __nonzero__ method, if not it uses a __len__ method. The instance is False if __nonzero__ is False or its length is 0.

like image 40
RemcoGerlich Avatar answered Sep 30 '22 04:09

RemcoGerlich