Hey,
Are you using the latest version of Numba? I do get a warning that the parallel=True isn’t able to do anything with this function, but that’s fine. Other than that it seems to work correct for me, but perhaps you meant something else, the formatting of the code in your post is a little off.
Using Numba 0.54.1.
from numba import njit
@numba.njit(parallel=True)
def test(model):
d = {}
if model == "foo":
d[2] = 1
x = 2
return x,d
Not entering the if-branch results in:
test("sar")
(2, DictType[int64,int64]<iv=None>({}))
And entering it:
test("foo")
(2, DictType[int64,int64]<iv=None>({2: 1}))
It’s always worth a try running with parallel=False to see if that works. Having it enabled definitely adds some restrictions
I was assuming that your x variable is declared outside the if-statement, since it’s always returned.
However, and this is a bit puzzling to me, if I do include it within the if-statement Numba runs fine whereas Python rightfully complains about it being undefined…
from numba import njit
def test_py(model):
d = {}
if model == "foo":
d[2] = 1
x = 2
return x,d
test_nb = njit(parallel=True)(test_py)
test_py("sar")
test_nb("sar")
Why does Numba return x=2 in this case?
Printing x before the if makes it crash because it’s undefined, so it’s not using some rogue global variable. Adding an else: x=1 clause correctly makes it return x=1.
Adding a print in the if-statement also shows that it never, unexpectedly, does enter there, since there’s nothing being printed:
def test_py(model):
print("before:", model)
if model == "foo":
x = 2
print("within-if:", model, x)
else:
print("within-else:", model, x)
print("after:", model, x)
return x
test_nb = njit(parallel=False)(test_py)
test_nb("sar")
Returns 2 and prints:
before: sar
within-else: sar 2
after: sar 2
Am I missing something?
Regards,
Rutger