Numba 函数签名,允许不同类型

时间:2021-05-27 22:07:11

标签: function numpy signature numba

我有一个属性 sources 的类,可以定义也不能定义。在使用 numba 之前,我将变量 sources 未定义时设置为 None,否则就是一个 numpy 数组。

现在,numba 似乎不允许这种行为。这样对吗?我虽然使用布尔变量作为解决方法,但这与函数(属性)source 的签名相混淆:

import numba 
from numba.experimental import jitclass
import numpy as np


spec = [
    ("_is_source_none", numba.bool_),
    ("_sources", numba.int32[:, :])
]


@jitclass(spec)
class MyClass:

    def __init__(self, sources: np.array):
        # Numba does not allow to set a var to None so we need an external variable to track it
        self._is_source_none = True if sources is None else False
        self._sources = sources.astype(np.int32) if sources is not None else np.zeros(shape=(50, 50), dtype=np.int32)

    @property
    def sources(self):
        if self._is_source_none:
            return None
        else:
            return self.sources

if __name__ == "__main__":

    MyClass(
        sources=None
    )

错误:

numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython mode backend)
Failed in nopython mode pipeline (step: nopython frontend)
Failed in nopython mode pipeline (step: nopython frontend)
Internal error at resolving type of attribute "sources" of "self".
Failed in nopython mode pipeline (step: nopython frontend)
compiler re-entrant to the same function signature
During: typing of get attribute at <input> (25)
Enable logging at debug level for details.
File "<input>", line 25:
<source missing, REPL/exec in use?>
During: typing of get attribute at <string> (3)
During: typing of get attribute at <string> (3)
File "<string>", line 3:
<source missing, REPL/exec in use?>

这在 Numba 中是否可行?

1 个答案:

答案 0 :(得分:0)

你得到的错误与 None 和输入无关。这是因为成员函数 self.sources 中的 sources 没有被声明或初始化,而 self._sources 是并且应该被使用。

注意 Numba 实际上支持使用 None 类型的 optional 值。您可以在 Numba documentation 中找到更多信息。

相关问题