Is there a way to include string attributes in numba jitclass?

Question:

I understand strings are now supported by numba, but could not find any documentation for how to use strings with jitclass and was unable to figure it out.

How do you create string attributes with jitclass?

(This hack was pre-string support and fairly messy: How can I pass string type in class in numba jitclass python?)

I have tried unicode_type, char, char[:], uint8, str — basically everything I can think of.

COND_SPEC = [
    ('feature',nb.unicode_type),
    ('val', nb.unicode_type)
]

@jitclass(COND_SPEC)
class Cond:
    """ Class implementing conditional. """

    def __init__(self, feature, val):
        self.feature = feature
        self.val = val

The class compiles, but declaring an instance of the class produces an error:

c = Cond('education','HS-grad')
numba.errors.LoweringError: Failed in nopython mode pipeline (step: nopython mode backend)
Cannot cast unicode_type to int8: %".37" = load {i8*, i64, i32, i64, i8*, i8*}, {i8*, i64, i32, i64, i8*, i8*}* %"feature"

File "<ipython-input-19-aaeb1c1955cb>", line 12:
    def __init__(self, feature, val):
        self.feature = feature
        ^

[1] During: lowering "(self).feature = feature" at <ipython-input-19-aaeb1c1955cb> (12)
[2] During: resolving callee type: jitclass.Cond#7f9c36758a18<feature:int8,val:int8>
[3] During: typing of call at <string> (3)

--%<----------------------------------------------------------------------------


File "<string>", line 3:
<source missing, REPL/exec in use?>
Asked By: Ilan

||

Answers:

I believe this is numba.types.string:

import numba as nb
from numba import jitclass

COND_SPEC = [
    ('feature', nb.types.string),
    ('val', nb.types.string)
]

@jitclass(COND_SPEC)
class Cond:
    """ Class implementing conditional. """

    def __init__(self, feature, val):
        self.feature = feature
        self.val = val
        
c = Cond('Hello', 'world')
print(c.feature, c.val)

>>>Hello world
Answered By: Jacques Gaudin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.