How can I let numba treat a custom class as a float? A minimal examle
import numba
import numpy as np
class MyFloat:
def __init__(self, f):
self.f = f
def __float__(self) -> float:
return float(f)
# ... in the actual implementation more is defined to make the class work like a float
s = 1.1
x = np.array([1,2,3.])
m = MyFloat(1.12)
@numba.jit(nopython=True)
def f(x, a):
return a + x**2
f(s, 2) # works!
f(x, 2) # works!
f(m, 2) # fails with TypingError: non-precise type pyobject
I can use forceobj=True to make the call f(m, 2) work, but that makes the calls to f(s, 2) and f(x, 2) very slow. Is there a way to specify that numba should treat objects of type MyFloat like a Python float (with conversion by calling __float__)?
I have read the Interval example at Example: an interval type — Numba 0.52.0.dev0+274.g626b40e-py3.7-linux-x86_64.egg documentation. But there it looks like one would have to teach numba about all the operations one could do with a MyFloat, instead of converting m to a float and then using the normal jitted method.