Why numpy.array gives an error in jitclass numba?

I'm trying to initialize a matrix with np.array in jitclass, but it just give me an error

for instance :

from numba.experimental import jitclass
from numba import int32, float64
import numpy as np

spec = [('n',float64[:,:])]

@jitclass(spec)
class myclass(object):

  def __init__(self ):
    self.n = np.array([[0.,1],[2,3],[4,5]])

if __name__ == '__main__':
    pop = myclass()

give me :

Traceback (most recent call last):
  File "C:/Users/maxime/Desktop/SESAME/PycharmProjects/LargeScale_2021_04_23/di.py", line 14, in <module>
    pop = myclass()
  File "C:\Python389\lib\site-packages\numba\experimental\jitclass\base.py", line 124, in __call__
    return cls._ctor(*bind.args[1:], **bind.kwargs)
  File "C:\Python389\lib\site-packages\numba\core\dispatcher.py", line 482, in _compile_for_args
    error_rewrite(e, 'typing')
  File "C:\Python389\lib\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)
Internal error at <numba.core.typeinfer.CallConstraint object at 0x000002A07F85BF40>.
Failed in nopython mode pipeline (step: native lowering)

Enable logging at debug level for details.

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

I don't understand why I cannot initiate my matrix.

I found this workaround:

from numba.experimental import jitclass
from numba import int32, float64
import numpy as np

spec = [('n',float64[:,:])]

@jitclass(spec)
class myclass(object):

  def __init__(self ):
    # self.n = np.array([[0.,1],[2,3],[4,5]])
    self.n = np.vstack((np.array([0., 1]), np.array([2., 3]), np.array([4., 5])))

if __name__ == '__main__':
    pop = myclass()
    print(pop.n)    

But I would prefer use directly the array function.


You should declare at least one float in each list, as you do in your workaround, so that Numba can infer a unique type for the array:

self.n = np.array([[0.,1],[2.,3],[4.,5]])

Declaring the type also helps:

self.n = np.array([[0,1],[2,3],[4,5]], dtype=nb.float64)