Is it possible to use python.locals() with numba?

50 Views Asked by At

I'm working on a python function that dynamically creates and uses variables. When i try to speed it up with numba I get this error message: 'numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend) Untyped global name 'locals': Cannot determine Numba type of <class 'builtin_function_or_method'>'

import numba

@numba.njit
def make_variables():
    for i in range(6, 9):
        locals()[f"my_variable_{i}"] = i
    for i in range(6, 9):
        res = locals()[f"my_variable_{i}"] + 2
        yield res

print(list(make_variables()))
1

There are 1 best solutions below

0
Talleros On

Solution with dictonary instead of locals()

import numba

@numba.njit
def dynamic_dict():
    my_dict = {}
    for i in range(6, 9):
        key = f"my_key_{i}"
        value = i
        my_dict[key] = value

    for i in range(6, 9):
        yield my_dict[f"my_key_{i}"] + 2

print(list(dynamic_dict()))