How to create node class for a tree structure with jitclass

I am trying to use jitclass with node class that is used for a tree structure. The problem is that I am not able to store the parent object reference. I tried types.pyobject but wasn’t successful.

Reproducing code example:

spec = [('parent', types.optional(types.pyobject)),
       ('name', types.unicode_type)]
@jitclass(spec)
class Nodes:
    def __init__(self, parent, name):
        self.parent = parent
        self.name = name

p = Nodes(None, 'parent')
c1 = Nodes(p, 'child1')
c2 = Nodes(p, 'child2')
c3 = Nodes(p, 'child3')

Error message:

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Internal error at <numba.typeinfer.CallConstraint object at 0x0000015A14537E80>.
Failed in nopython mode pipeline (step: nopython mode backend)
Cannot cast instance.jitclass.Nodes#15a151cd9b0<parent:OptionalType(pyobject) i.e. the type ‘pyobject or None’,name:unicode_type> to OptionalType(pyobject) i.e. the type ‘pyobject or None’: %".31" = load {i8*, {{i8*, i8}, {i8*, i64, i32, i32, i64, i8*, i8*}}}, {i8, {{i8*, i8}, {i8*, i64, i32, i32, i64, i8*, i8*}}} %“parent”

File “”, line 6:
def init(self, parent, name):
self.parent = parent
^

Hi rashid,
welcome to the forum! :slight_smile:

Now this is a bit of a head scratcher. You would want the type of self.parent to be the type associated with the Nodes class, but that is not (obviously) available when you are defining the type spec needed for the compilation in order to create the type.

Is using jitclass ultimately necessary here or could you get away with a simpler, more basic data structure? (Obviously depends a little on what you are planning to do going from here)

That said, I think there is a possible solution to your problem hidden in the numba test suite

It seems like there is a way to delay the type specification so that jitclasses can contain members of their own type. @sklam probably has more insight into this :slight_smile:

1 Like

Perhaps this example for a linked list using jitclass will help: