Why setting the custom class __array_priority__ above zero makes the comparison with numpy.float64 wrong?
Consider a silly subclass float
:
class Bar(float):
__array_priority__ = 2
Now we are trying to compare an instance Bar
with numpy float64:
import numpy as np x = np.float64(1) y = Bar(2.0) x < y False
Launched, we will try the following
import numpy as np
def make_class(x):
"""Get a float subclass with adjustable __array_priority"""
class Bar(float):
__array_priority__ = x
return Bar
def test(priorities):
"""Check float comparison for various __array_priority__ values"""
results = []
for priority in priorities:
x = np.float64(1)
Bar = make_class(priority)
y = Bar(2.0)
results.append(x < y)
for p, v in zip(priorities, results):
print("{} {}".format(p, v))
Triggering test
on multiple selection values ββ(note that __array_priority__
of np.float64
-1000000.0
)
__array_priority__ | x < y
--------------------------------------------------
-10000000 | True
-1000001.0 | True
-1000000.0 | True (same __array_priority__ as float64)
-999999.0 | True
-1 | True
0 | True
0.3 | False
1 | False
2 | False
As you can see, if __array_priority__
greater than 0
, no comparison is made. Whether our custom is __array_priority__
more or less np.float64
__array_priority__
does not matter.
Some of my colleagues have tried this on their machines and we found this problem only occurs with python 2.7.6
(64 bit) and numpy 1.9.2
. Using either this version of python or just this version of numpy does not reproduce the error. This only happens when both of these versions are used together.
Why does setting a custom __array_priority__
higher or lower 0
change the comparison behavior, causing it to work unexpectedly in cases >0
in this combination of python and numpy versions?
Note that replacing the comparison x < y
with y > x
results in the expected behavior as @ GyΓΆrgy Solymosi mentioned below.
source to share