numba jitclass 中的对象比较

Object comparison in numba jitclass

如何比较两个 numba jitclass 对象以查看它们是否相同?

我有以下代码

from numba import jitclass
import numba

node_type = numba.deferred_type()
DoubleLinkedNode_spec = [
  ('value', numba.optional(numba.typeof(1.0))),
  ('prev', numba.optional(node_type)),
  ('next', numba.optional(node_type))
]

@jitclass(DoubleLinkedNode_spec)
class DoubleLinkedNode(object):
  def __init__(self, value, prev, next):
    self.value = value
    self.prev = prev
    self.next = next

node_type.define(DoubleLinkedNode.class_type.instance_type)

n1 = DoubleLinkedNode(1.0, None, None)
n2 = DoubleLinkedNode(2.0, n1, None)
n1.next = n2
print(f'{n2}\n{n2.prev.next}')
#outputs: 
#  <numba.jitclass.boxing.DoubleLinkedNode object at 0x7fbf26923850>
#  <numba.jitclass.boxing.DoubleLinkedNode object at 0x7fbf256b3cf0>
print(f'Next is None. n1: {n1.next is None}   n2: {n2.next is None}')
#outputs: 
#  Next is None. n1: False   n2: True

这是双链表的标准节点。

is 运算符不起作用,因为它们不在同一内存地址中。

  1. 为什么会这样?
  2. 那我怎么比较两个对象呢?
  3. is None 似乎有效。但是我能相信吗?

Dunder 方法不能与 jitclasses 一起正常工作所以我实现了类似于 __eq__.

的东西
from numba.experimental import jitclass
import numba

node_type = numba.deferred_type()
DoubleLinkedNode_spec = [
    ('value', numba.optional(numba.typeof(1.0))),
    ('prev', numba.optional(node_type)),
    ('next', numba.optional(node_type))
]

@jitclass(DoubleLinkedNode_spec)
class DoubleLinkedNode(object):
    def __init__(self, value, prev, next):
        self.value = value
        self.prev = prev
        self.next = next

    def equal(self, other):
        return self.prevs_eq(other) and self.nexts_eq(other)

    def prevs_eq(self, other):
        while True:
            if self.prev is None:
                return self.value == other.value
            if not self.value == other.value:
                return False

            self = self.prev
            other = other.prev

    def nexts_eq(self, other):
        while True:
            if self.next is None:
                return self.value == other.value
            if not self.value == other.value:
                return False

            self = self.next
            other = other.next

node_type.define(DoubleLinkedNode.class_type.instance_type)

n1 = DoubleLinkedNode(1.0, None, None)
n2 = DoubleLinkedNode(2.0, n1, None)
n1.next = n2

print(f'{n2.equal(n2.prev.next)}')
# True

你必须调用不优雅的equal方法,但如果你将它重命名为__eq__它根本不起作用。这适用于我目前测试过的内容。