How to define `bool` conversion for custom data type?
Question:
I’m extending Python with a new type, and looking New Types section of Python manual I don’t see anything for bool conversion. How do I specify how my type is converted to a bool?
For instance in the example below native numpy type to is interpreted as Python bool somehow
import numpy as np
if (np.array(False)):
print 'hi'
else:
print 'hey'
Looking at bytecode, this corresponds to POP_JUMP_IF_FALSE
but this doesn’t seem useful for tracking down the conversion logic.
Answers:
In the Python documentation, under Special Method Names, you can see that the .__bool__()
method does exactly this.
class MyType(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value != 0
If you are still using Python 2.x then the method name is __nonzero__
instead of __bool__
(see Python 2.7 Documentation).
I’m extending Python with a new type, and looking New Types section of Python manual I don’t see anything for bool conversion. How do I specify how my type is converted to a bool?
For instance in the example below native numpy type to is interpreted as Python bool somehow
import numpy as np
if (np.array(False)):
print 'hi'
else:
print 'hey'
Looking at bytecode, this corresponds to POP_JUMP_IF_FALSE
but this doesn’t seem useful for tracking down the conversion logic.
In the Python documentation, under Special Method Names, you can see that the .__bool__()
method does exactly this.
class MyType(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value != 0
If you are still using Python 2.x then the method name is __nonzero__
instead of __bool__
(see Python 2.7 Documentation).