英文:
Python, numba, class with field of its own type
问题
I'm trying to use numba's jitclass
on a class that has a field of its own type.
The below code does not work because Foo
is not defined.
from numba.experimental import jitclass
@jitclass
class Foo:
a: int
pred: 'Foo'
def __init__(self, pred: 'Foo'):
self.a = 1
self.pred = pred
if __name__ == "__main__":
x = Foo(None)
Replacing Foo
with object also does not work. Additionally, I need to be able to pass None in one instance.
Is there a way to make this work?
The only other idea I have is to store pred
in an external dictionary.
英文:
I'm trying to use numba's jitclass
on a class that has a field of its own type.
The below code does not work because Foo
is not defined.
from numba.experimental import jitclass
@jitclass
class Foo:
a: int
pred: 'Foo'
def __init__(self, pred: 'Foo'):
self.a = 1
self.pred = pred
if __name__ == "__main__":
x = Foo(None)
Replacing Foo
with object also does not work. Additionally, I need to be able to pass None in one instance.
Is there a way to make this work?
The only other idea I have is to store pred
in an external dictionary.
答案1
得分: 2
我认为这应该能满足你的需求:
我认为这应该能满足你的需求:
from numba.experimental import jitclass
from numba import deferred_type, int64, optional
foo_type = deferred_type()
spec = dict()
spec['a'] = int64
spec['pred'] = optional(foo_type)
@jitclass(spec)
class Foo(object):
def __init__(self, pred):
self.a = 1
self.pred = pred
foo_type.define(Foo.class_type.instance_type)
x = Foo(None)
y = Foo(x)
这基于[此示例](https://github.com/numba/numba/blob/fdbe264706881d19e97494e5ca794c540479a4d0/examples/linkedlist.py)。
英文:
I think this should do what you want:
from numba.experimental import jitclass
from numba import deferred_type, int64, optional
foo_type = deferred_type()
spec = dict()
spec['a'] = int64
spec['pred'] = optional(foo_type)
@jitclass(spec)
class Foo(object):
def __init__(self, pred):
self.a = 1
self.pred = pred
foo_type.define(Foo.class_type.instance_type)
x = Foo(None)
y = Foo(x)
It is based on this example.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论