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

Numba function signature that allow different types

我有一个 class,其属性 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 中甚至可能吗?

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

注意 Numba 实际上支持使用 optional 类型的 None 值。您可以在 Numba documentation.

中找到更多信息