Reputation: 23647
TL;DR: When decorating a class with @numba.jitclass
special methods such as __add__
do not appear in instances of the class, while other methods work normally. Why does this happen?
Consider the following class declaration:
import numba as nb
dual_spec = [('x', nb.float64), ('y', nb.float64)]
@nb.jitclass(dual_spec)
class xy:
def __init__(self, x, y):
self.x = x
self.y = y
def addition(self, other):
return xy(self.x + other.x, self.y + other.y)
def __add__(self, other):
return xy(self.x + other.x, self.y + other.y)
Without the decorator the class works perfectly fine. Due to the __add__
method expressions like xy(1, 2) + xy(3, 4)
are possible and return expected results. However, with the decorator I get the following error message:
>>> xy(1, 2) + xy(3, 4) # TypeError: unsupported operand type(s) for +: 'xy' and 'xy'
>>> xy(1, 2).addition(xy(3, 4)) # But this works nicely
It looks like the __add__
method is not present in xy
objects:
>>> xy(1, 2).__add__ # AttributeError: 'xy' object has no attribute '__add__'
But the method is present in the class:
>>> xy.__add__ # <function __main__.xy.__add__>
What is numba doing to the __add__
method during instantiation? Is there another way to enable operators for jitted classes so that I can write xy(1, 2) + xy(3, 4)
?
Upvotes: 3
Views: 372
Reputation: 52286
Currently (as of numba version 0.33
) operator overloading on jitclasses is not supported, open issue here:
https://github.com/numba/numba/issues/1606#issuecomment-284552746
I don't know the exact internals, but it is likely the method is simply being discarded. Note that when you instantiate at a jitclass
you are not directly instantiating the python class but instead are getting a wrapper around the low-level numba type.
v = xy(1, 2)
v
Out[8]: <numba.jitclass.boxing.xy at 0x2e700274950>
v._numba_type_
Out[9]: instance.jitclass.xy#2e77d394438<x:float64,y:float64>
Upvotes: 4