【发布时间】:2021-12-27 22:07:15
【问题描述】:
我在使用带有 numba 的 jitclass 装饰器来“编译”我的 python 代码时遇到问题。在有人告诉我阅读文档之前,我有但不知道在哪里看,所以如果你要告诉我,请引导我到 numba 文档中的特定点:)
我现在拥有的一个例子(如果你尝试运行它,你需要使用 -O 标志让它退出调试模式):
# class in separate file
print(f"debug state = {__debug__}\n")
if not __debug__:
from numba import int64, float64 # import types
from numba import njit
from numba.experimental import jitclass
spec = [
('init_val', int64),
('spacing', float64),
]
def blank_dec(*args, **kwargs):
return args[0]
dec = blank_dec if __debug__ else jitclass(spec)
@dec
class foo:
def __init__(self, init_val, spacing):
self.property = init_val
self.spacing = spacing
def foobar(self):
try:
# method here, just adding numbers
except Exception as e:
if __debug__:
print(e) # this line appears to give trouble, error below
else:
sys.stderr.write(e) # this also causes issues
#main file
if __name__ == "__main__":
foobar = foo(16, 1E-05)
这代表了我的设置并重现了我得到的错误。这是错误(用“####### 编辑的文件路径):
Traceback (most recent call last):
File "main.py", line 4, in <module>
foobar = tc.foo(16, 1E-05)
File "#######/anaconda3/envs/PHYS/lib/python3.8/site-packages/numba/experimental/jitclass/base.py", line 124, in __call__
return cls._ctor(*bind.args[1:], **bind.kwargs)
File "#######/anaconda3/envs/PHYS/lib/python3.8/site-packages/numba/core/dispatcher.py", line 482, in _compile_for_args
error_rewrite(e, 'typing')
File ""#######/anaconda3/envs/PHYS/lib/python3.8/site-packages/numba/core/dispatcher.py", line 423, in error_rewrite
raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Failed in nopython mode pipeline (step: nopython frontend)
Cannot resolve setattr (instance.jitclass.foo#7f433450f1f0<init_val:int64,spacing:float64>).property = int64
File "testclass.py", line 20:
def __init__(self, init_val, spacing):
self.property = init_val
^
During: typing of set attribute 'property' at "#######/testing/testclass.py (20)
File "testclass.py", line 20:
def __init__(self, init_val, spacing):
self.property = init_val
^
During: resolving callee type: jitclass.foo#7f433450f1f0<init_val:int64,spacing:float64> During: typing of call at <string> (3)
During: resolving callee type: jitclass.foo#7f433450f1f0<init_val:int64,spacing:float64> During: typing of call at <string> (3)
File "<string>", line 3: <source missing, REPL/exec in use?>
它似乎在抱怨字符串,但我不明白为什么。我看到另一个帖子说我需要使用编码来格式化字符串,但这似乎不是我的问题。
我也尝试删除 try-except 块和初始打印语句 - 因为我认为问题可能与打印语句有关,但这似乎无法解决问题。
非常感谢任何帮助!
【问题讨论】:
-
为什么要将所有这些
if not __debug__:添加到您的示例中?是否相关?没有它,代码仍然会失败吗?请始终提供minimal reproducible example -
这与我正在处理的项目有关,尽管没有它问题仍然存在。我想我应该留下它,以防万一出现我看不到的问题。