Replacement of dict type for numba as parameters of a python function

2.6k Views Asked by At

In my code, there are a lot of parameters which are constant during the running. I defined a dict type variable to store them. But I find that numba cannot support dict.

What is a better way to solve this?

2

There are 2 best solutions below

2
On BEST ANSWER

Assuming you have a function like this and you are fine by accessing it as attribute instead of by subscript:

import numba as nb

@nb.njit
def func(config):
    return config.c

You could use a collections.namedtuple here (like @JoshAdel mentioned):

import numpy as np
from collections import namedtuple

conf = namedtuple('conf', ['a', 'b', 'c'])

func(conf(1, 2.0, np.array([1,2,3], dtype=np.int64)))
# array([1, 2, 3], dtype=int64)

Or a jitclass:

spec = [('a', nb.int64),
        ('b', nb.float64),
        ('c', nb.int64[:])]

@nb.jitclass(spec)
class Conf:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

func(Conf(1, 2.0, np.array([1,2,3], dtype=np.int64)))
# array([1, 2, 3], dtype=int64)

These can't replace all functionalities of a dictionary but these allow to pass in "a lot of parameters" as one instance.

0
On

Numba supports namedtuples in nopython mode, which should be a good alternative to a dict for passing a large group of parameters into a numba jitted function.