首页 > 解决方案 > Numba:初始化一个 jitclass 装饰类的成员生成器

问题描述

在尝试使用如下所述初始化一个简单的类时,我遇到了两个问题,

# Python Version : 3.8.3
import numpy as np
# np.__version__ : 1.18.5
import numba as nb
# nb.__version__ : 0.50.1

mydict_like = nb.typed.Dict()
mydict_like['SomeKey'] = np.ones((100,6), dtype=np.float64)

myspecs = [('mydict', nb.typeof(mydict_like)),
#            ('tid_gen', #<----What Type??--->#)
          ]

@nb.experimental.jitclass(spec=myspecs)
class MyClass:
    def __init__(self):
        pass

    def _initialiser(self, new_dict):
        self.mydict = new_dict
        # This is where the initialisation of the generator is supposed to 
        # take place. Although i am unsure of what type would be of the 
        # the attribute `tid_gen` to be difined in `myspecs`.
        # self.tid_gen = self._unique_id_generator()

    @staticmethod
    def _unique_id_generator():
        """
        At every next() call this generator needs to yield the next number.
        For Ex:
        - next(self.tid_gen) => 0
        - next(self.tid_gen) => 1
        - next(self.tid_gen) => 2
        - next(self.tid_gen) => 3
        - [next(self.tid_gen) for _ in range(5)] => [4,5,6,7,8]
        """
        n=0 #First Id
        while True:
            yield n
            n+=1

clsObj = MyClass()

# A new Dictionary
updated_dict = nb.typed.Dict()
updated_dict['RandomKey'] = np.ones((200,12), dtype=np.float64)

# clsObj._initialiser(new_dict=updated_dict) # TypeError: some keyword arguments unexpected :: Why??
clsObj._initialiser(updated_dict)
print(clsObj.mydict)

尽管目前这不是那么紧迫的问题,但我仍然想知道为什么会这样?

任何帮助将不胜感激:) 谢谢。

标签: pythonnumpyoptimizationjitnumba

解决方案


推荐阅读