Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding bool() for custom class [duplicate]

All I want is for bool(myInstance) to return False (and for myInstance to evaluate to False when in a conditional like if/or/and. I know how to override >, <, =)

I've tried this:

class test:
    def __bool__(self):
        return False

myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"

Any suggestions?

(I am using Python 2.6)

like image 535
Ponkadoodle Avatar asked Oct 09 '22 02:10

Ponkadoodle


2 Answers

Is this Python 2.x or Python 3.x? For Python 2.x you are looking to override __nonzero__ instead.

class test:
    def __nonzero__(self):
        return False
like image 71
Joe Holloway Avatar answered Oct 11 '22 15:10

Joe Holloway


If you want to keep your code forward compatible with python3 you could do something like this

class test:
    def __bool__(self):
        return False
    __nonzero__=__bool__
like image 69
John La Rooy Avatar answered Oct 11 '22 14:10

John La Rooy