function - 允许不同类型的 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 中是否可行?
解决方案
您得到的错误与 None 和打字无关。这是由于self.sources
在成员函数中sources
没有被声明或初始化,而self._sources
应该被使用。
注意 Numba 实际上支持None
使用optional
类型的值。您可以在Numba 文档中找到更多信息。
推荐阅读
- python - 日文字符无法从 Python3 中的 unicode 解码
- eslint - 值...不应该有额外的属性
- python - 将传感器读入python数组并用PHP解析
- javascript - React Native,值没有更新
- javascript - 我将如何修复此功能以根据日期更改月份?
- datagridview - 所选项目没有可显示的数据源
- bash - Bash:在循环时将目录名称设置为变量
- powerbi - Power BI 图表上的筛选值无效
- sql-server - 如何从具有 utf8 编码的文件中执行“SQL 任务”SSIS?
- laravel-8 - 我在 Dashboard.vue 中所做的更改没有被保存(Laravel Jetstream Inertia.js)