52

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
>>>
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
dividebyzero
  • 1,243
  • 2
  • 9
  • 17
  • Dup of [overriding bool() for custom class](http://stackoverflow.com/questions/2233786) – outis Jan 19 '12 at 11:08

1 Answers1

100

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
  • 574,206
  • 118
  • 941
  • 841
  • 1
    It is strange that I could not find that information anywhere else but in your answer. Thanks a lot ! – Mehmet Kaan ERKOÇ Mar 30 '22 at 13:24
  • 1
    @MehmetKaanERKOÇ The documentation for most of the magic methods is on the [data model page of the Python reference](https://docs.python.org/3/reference/datamodel.html). Differences between Python 2 and 3 are mostly documented in the [What's New page of Python 3.0](https://docs.python.org/3/whatsnew/3.0.html#operators-and-special-methods). I'll admit this is not easy to find if you don't know what you are looking for. – Sven Marnach Mar 30 '22 at 19:16