如何在Numba jitclass中正确使用字符串列表?已触发弃用警告
在Numba jitclass中包含字符串列表的正确方式
你在jitclass中使用types.List(types.unicode_type)触发了弃用警告,这是因为该类型属于Numba计划废弃的反射列表(reflected list),下面是正确的处理方式及替代方案:
触发的警告信息
:3: NumbaPendingDeprecationWarning:
Encountered the use of a type that is scheduled for deprecation: type 'reflected list' found for argument 'strings' of function 'DateTimeStringClass.init'.C:\numba\core\ir_utils.py:2172: NumbaPendingDeprecationWarning:
Encountered the use of a type that is scheduled for deprecation: type 'reflected list' found for argument 'strings' of function 'ctor'.
替代方案
方案1:使用Numba原生typed.List
Numba提供了原生类型化列表,需提前用numba.typed.List初始化,而非直接传入Python列表。修改后的代码如下:
import numpy as np from numba.experimental import jitclass from numba import types from numba.typed import List spec = [ ('datetime', types.NPDatetime('s')), ('strings', types.ListType(types.unicode_type)), # 替换为ListType ] @jitclass(spec) class DateTimeStringClass: def __init__(self, datetime, strings): self.datetime = datetime self.strings = strings # 示例用法:先创建Numba类型化列表 datetime_obj = np.datetime64('2024-03-02 02:00:00') string_list = List() for s in ['string1', '323', 'string3']: string_list.append(s) obj = DateTimeStringClass(datetime_obj, string_list)
方案2:改用numpy字符串数组
若字符串长度可控、无需动态增删元素,使用numpy字符串数组是更高效的选择,内存布局更紧凑:
import numpy as np from numba.experimental import jitclass from numba import types # 定义字符串类型:UnicodeCharSeq(长度)[:] 表示字符串数组 spec = [ ('datetime', types.NPDatetime('s')), ('strings', types.UnicodeCharSeq(10)[:]), # 假设最长字符串为10个字符 ] @jitclass(spec) class DateTimeStringClass: def __init__(self, datetime, strings): self.datetime = datetime self.strings = strings # 示例用法 datetime_obj = np.datetime64('2024-03-02 02:00:00') # 创建指定长度的numpy字符串数组,dtype='U10'对应长度10的Unicode字符串 string_array = np.array(['string1', '323', 'string3'], dtype='U10') obj = DateTimeStringClass(datetime_obj, string_array)
方案选择建议
- 需要动态增删元素:优先用Numba原生
typed.List,性能更优且支持容器操作。 - 元素数量固定、无需修改:选择numpy字符串数组,内存效率更高。
内容的提问来源于stack exchange,提问作者brokkoo
相关产品推荐
相关产品推荐

