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

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

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.

  1. from numba.experimental import jitclass
  2. @jitclass
  3. class Foo:
  4. a: int
  5. pred: 'Foo'
  6. def __init__(self, pred: 'Foo'):
  7. self.a = 1
  8. self.pred = pred
  9. if __name__ == "__main__":
  10. 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.

  1. from numba.experimental import jitclass
  2. @jitclass
  3. class Foo:
  4. a: int
  5. pred: 'Foo'
  6. def __init__(self, pred: 'Foo'):
  7. self.a = 1
  8. self.pred = pred
  9. if __name__ == "__main__":
  10. 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

我认为这应该能满足你的需求:

  1. 我认为这应该能满足你的需求
  2. from numba.experimental import jitclass
  3. from numba import deferred_type, int64, optional
  4. foo_type = deferred_type()
  5. spec = dict()
  6. spec['a'] = int64
  7. spec['pred'] = optional(foo_type)
  8. @jitclass(spec)
  9. class Foo(object):
  10. def __init__(self, pred):
  11. self.a = 1
  12. self.pred = pred
  13. foo_type.define(Foo.class_type.instance_type)
  14. x = Foo(None)
  15. y = Foo(x)
  16. 这基于[此示例](https://github.com/numba/numba/blob/fdbe264706881d19e97494e5ca794c540479a4d0/examples/linkedlist.py)
英文:

I think this should do what you want:

  1. from numba.experimental import jitclass
  2. from numba import deferred_type, int64, optional
  3. foo_type = deferred_type()
  4. spec = dict()
  5. spec['a'] = int64
  6. spec['pred'] = optional(foo_type)
  7. @jitclass(spec)
  8. class Foo(object):
  9. def __init__(self, pred):
  10. self.a = 1
  11. self.pred = pred
  12. foo_type.define(Foo.class_type.instance_type)
  13. x = Foo(None)
  14. 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:

确定