WZhao
WZhao

Reputation: 323

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

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?

Upvotes: 8

Views: 2778

Answers (2)

MSeifert
MSeifert

Reputation: 152637

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.

Upvotes: 5

JoshAdel
JoshAdel

Reputation: 68682

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.

Upvotes: 3

Related Questions