41

As we know, Python has boolean values for objects: If a class has a __len__ method, every instance of it for which __len__() happens to return 0 will be evaluated as a boolean False (for example, the empty list).

In fact, every iterable, empty custom object is evaluated as False if it appears in boolean expression.

Now suppose I have a class foo with attribute bar. How can I define its truth value, so that, say, it will be evaluated to True if bar % 2 == 0 and False otherwise?

For example:

myfoo = foo()
myfoo.bar = 3
def a(foo):
    if foo:
        print "spam"
    else:
        print "eggs"

so, a(myfoo) should print "eggs".


To close questions that are specifically about debugging an error caused by using the 3.x-specific approach in 2.x, use How can I implement conversion to boolean for classes in 2.x? Why doesn't the "__bool__" magic method work?.

1
  • See also: __nonzero__() Commented Aug 18, 2015 at 23:27

2 Answers 2

59

Python 2.x

Use the __nonzero__ magic method. It's called automatically by Python when evaluating an object in a boolean context. It must return a boolean that will be used as the value to evaluate.

E.G :

class Foo(object):

    def __init__(self, bar) :
        self.bar = bar

    def __nonzero__(self) :
        return self.bar % 2 == 0

if __name__ == "__main__":
     if (Foo(2)) : print "yess !"

Python 3.x

Use __bool__ instead, in the same way.

Sign up to request clarification or add additional context in comments.

1 Comment

Would you object to further editing this, to prioritize the 3.x answer?
38

In Python 2, use __nonzero__:

Refer to the Python 2 docs for __nonzero__.

class foo(object):
    def __nonzero__( self) :
        return self.bar % 2 == 0

def a(foo):
    if foo:
        print "spam"
    else:
        print "eggs"

def main():
    myfoo = foo()
    myfoo.bar = 3
    a(myfoo)

if __name__ == "__main__":
    main()

1 Comment

Please refer to other answer for Python 3, this answer applies exclusively to Python 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.