Defining "boolness" of a class in python

boolean, class, python, python-2.7, python-2.x

Solution

For Python 2-3 compatibility, add a line after the class definition block to alias the method:

class Foo(object):
    ...

Foo.__nonzero__ = Foo.__bool__

or include the alias directly in the class definition:

class Foo(object):
    def __bool__(self):
        ...

    __nonzero__ = __bool__

Of course this would also work the other way around, but I think the name `__nonzero__` is just a legacy of the original C-ishness of Python's interpretation of objects as truthy or falsy based on their equivalence with zero. Just add the statement above and the code will work with regardless of the version of Python (and the `__nonzero__` definition can be dropped when support for 2.x is no longer needed).

Problem

Why doesn't this work as one may have naively expected? ``` class Foo(object): def __init__(self): self.bar = 3 def __bool__(self): return self.bar > 10 foo = Foo() if foo: print 'x' else: print 'y' ``` (The output is `x`)

Original source

Related problems