How to specify numba jitclass when the class' attribute contains an instance of self

Viewed 836

I have a simple Python class:

class Node(object):
    def __init__(self):
        self._left = self
        self._right = self

    @property
    def left(self):
        return self._left

    @left.setter
    def left(self, value):
        self._left = value

    @property
    def right(self):
        return self._right

    @right.setter
    def right(self, value):
        self._right = value

I would like to jit this class but it isn't clear how to define the types when self._left and self._right are of Node object type. I came across this other answer that uses .class_type.instance_type but that example only refers to a class attribute that contains a different class instance. In my case, since Node is not defined yet, I cannot declare the following spec:

spec=[("_left", Node.class_type.instance_type),
      ("_right", Node.class_type.instance_type),
     ]

@jitclass(spec)
class Node(object):
1 Answers

Based on this example - numba has a deferred_type function for this case.

node_type = numba.deferred_type()
spec=[
    ("_left", node_type),
    ("_right", node_type),
]

@jitclass(spec)
class Node:
    # omitted

# define the deferred type
node_type.define(Node.class_type.instance_type)

# class can be used!
a = Node()
b = Node()
a.left = b
Related