Trying to check the identity of two jitclass instances attributes, I found this strange behaviour compared to ordinary python classes. Numba jitclass return False on its own instance attribute identity check where ordinary python classes work as expected.
import numba
class MyClass(object):
def __init__(self, x):
self.x = x
spec = [('x', numba.double)]
@numba.jitclass(spec)
class MyJitClass(object):
def __init__(self, x):
self.x = x
a = MyClass(1)
b = MyJitClass(1)
Now checking the identity:
>>> a.x is a.x
True
>>> b.x is b.x
False
Any idea why this happens? And how I should check whether two jitclass attributes reference to the same object?
Let me start with quoting the jitclass
documentation:
The data of a jitclass instance is allocated on the heap as a C-compatible structure so that any compiled functions can have direct access to the underlying data, bypassing the interpreter.
This means the data of the class (x
in this case) are not directly accessible by the Python interpreter. However, a transparent solution to solve this problem is to use properties. Numba seems to have taken this approach.
Every time you access b.x
, under the hood a function is invoked that returns a Python object wrapping the value of x
. The class does not store the object, so each access to x
returns a new object. Verify this by calling id(b.x)
- it will return a different ID every time.
We can simulate the behavior of the jit class with this:
class MyClass(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return float(self._x)
And how I should check whether two jitclass attributes reference to the same object?
Well, they don't. The jitclass attributes don't store objects, just data.