Reputation: 2446
If statements in Python allow you to do something like:
if not x:
print "X is false."
This works if you're using an empty list, an empty dictionary, None, 0, etc, but what if you have your own custom class? Can you assign a false value for that class so that in the same style of conditional, it will return false?
Upvotes: 29
Views: 26668
Reputation: 110202
Since Python 3, you need to implement the __bool__
method on your class. This should return True or False to determine the truth value:
class MyClass:
def __init__(self, val):
self.val = val
def __bool__(self):
return self.val != 0 #This is an example, you can use any condition
x = MyClass(0)
if not x:
print('x is false')
If __bool__
has not been defined, the implementation will call __len__
and the instance will be considered True if it returned a nonzero value. If __len__
hasn't been defined either, all instances will be considered True.
For further reading:
In Python 2, the special method __nonzero__
was used instead of __bool__
.
Upvotes: 43
Reputation: 49886
class Foo:
def __nonzero__(self): return False
__bool__ = __nonzero__ # this is for python3
In [254]: if Foo():
.....: print 'Yeah'
.....: else: print 'Nay'
.....:
Nay
Or, if you want to be ultra-portable, you can define __len__
only, which will have the same effect in both languages, but that has the (potential) downside that it implies that your object has a meaningful measure of length (which it may not).
This will work for any instance, depending on the actual logic you put in the method.
Upvotes: 10