使用Numba @jit(nopython=True)时遇FORMAT_WITH_SPEC不支持错误
问题原因
UnsupportedBytecodeError: Use of unsupported opcode (FORMAT_WITH_SPEC) 错误是因为你在@jit(nopython=True)修饰的函数中使用了带格式说明符的f-string(即f"..."里的:.2f这类格式化语法),Numba的nopython模式不支持这类字节码操作。
解决方案
将带格式说明符的f-string替换为Numba支持的str.format()方法,修改代码中的print语句:
原代码片段:
if verbose: print(f"nodes checked {checkednodes} out of {len(nodes1)},{len(nodes2)} - unrecognized nodes ~ {(1-checkednodes/len(nodes1))*100:.2f}%")
替换为:
if verbose: unrecognized_ratio = (1 - checkednodes / len(nodes1)) * 100 print("nodes checked {} out of {},{} - unrecognized nodes ~ {:.2f}%".format( checkednodes, len(nodes1), len(nodes2), unrecognized_ratio ))
额外提示
- Numba的nopython模式对Python高级语法支持有限,jit函数内尽量避免复杂字符串操作、动态结构修改。
- 内部函数
conndirections里的列表比较dr1==dr2可以正常运行,若追求性能,可将列表替换为NumPy数组,进一步提升计算效率。
内容的提问来源于stack exchange,提问作者alessandro
相关产品推荐
相关产品推荐

