Python,numba,具有自身类型字段的类

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月27日 21:55:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定