49

Possible Duplicate:
defining “boolness” of a class in python

I thought this should print "False", why is it printing "True"?

>>> class Foo(object):
...   def __bool__(self):
...     return False
... 
>>> f = Foo()
>>> if f:
...   print "True"
... else:
...   print "False"
... 
True
>>>
Community
  • 1
  • 1
dividebyzero
  • 1,153
  • 2
  • 8
  • 16
  • Dup of [overriding bool() for custom class](http://stackoverflow.com/questions/2233786) – outis Jan 19 '12 at 11:08

1 Answers1

90

You should define __nonzero__() in Python 2.x. It was only renamed to __bool__() in Python 3.x. (The name __nonzero__() actually predates the introduction of the bool type by many years.)

Sven Marnach
  • 483,142
  • 107
  • 864
  • 776