Fausto Arinos Barbuto
Fausto Arinos Barbuto

Reputation: 398

Classes, strings and numba

A couple of days ago I posted a question about the use of numba and strings. Someone kindly suggested a solution -- which worked, but produced more warnings than actual outputs. Revisiting my post, I realized that I made it way more complicated than I should, and in doing so I hid the actual problem I guess. I will try to make it minimalistic this time.

I'm trying to pass a list of strings to _init_() and make it an attribute of that class. I have tried that countless times and ways. The best approach I have gotten so far is the following:

from numba import types
from numba.experimental import jitclass

spec = [('S', types.ListType(types.unicode_type)), \
        ('Scopy', types.ListType(types.unicode_type))]

@jitclass(spec)
class Test(object):
    def __init__(self, S):
        #self.Scopy = S.copy()
        #print(self.Scopy)
        return print(S)

A = ["a", "b"]
Test(A)

The script above produces one single output line (as expected) and (not exaggerating) over a dozen warning lines.

The problem begins when I uncomment the first two lines of __init__(), the ones that create a copy of the list as a class attribute and print it. Now an error occurs and no valid output is produced. I wonder what's wrong. I tried several approaches and their combinations, but nothing works. I suspect that .copy() is the problem, since the script works (poorly, however) if I left the first two lines commented.

Python 3.8.5, numba 0.53.0, Xubuntu 20.04-64.

Thanks for any help.

Upvotes: 0

Views: 50

Answers (1)

aerobiomat
aerobiomat

Reputation: 3437

Passing a Python list is deprecated. You should pass a typed.List instead.

This code:

@nb.experimental.jitclass(spec)
class Test(object):

    def __init__(self, S):
        self.Scopy = S.copy()
        print(self.Scopy)
        print(S)

A = nb.typed.List(["a", "b"])
Test(A)

Produces:

[a, b]
[a, b]

Upvotes: 1

Related Questions