New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type inference error for dict when using default value #4244
Comments
@ivirshup thanks for reporting this! In essence the typed dictionary is of undefined type until you add something to it. In that case, the dict will be refined and will have a fixed type associated with it's keys and values. However, in this case it seems like the refinement is currently not working for cc @sklam |
No worries. I ended up figuring out that I could set the type of the |
@ivirshup good to hear, will still leave this open to track the bug |
Minor update – I've come across a similar case where type inference does work: import numba
@numba.njit
def foo(x):
d = {}
for k in x:
if k in d:
d[k] += 1
else:
d[k] = 1
return d
d = foo(list("aabc"))
d
# DictType[unicode_type,int64]({a: 2, b: 1, c: 1})
# So we can just do:
@numba.njit
def get(d, k, default=None):
if k in d:
return d[k]
else:
return default
assert get(d, "d") is None
assert get(d, "d", 6) == 6
assert get(d, "a") == 2
assert get(d, "a", 6) == 2 |
A similar issue when interfacing with numpy arrays and # crashes
@njit("float64[:](int64[:], float64[:], int64[:])")
def a(x, y, z):
d = Dict.empty(key_type=types.int64, value_type=types.float64)
for i in range(len(x)):
d[x[i]] = y[i]
return np.array([d.get(_z, default=0.) for _z in z]) Error message:
|
Reporting a bug
the change log (https://github.com/numba/numba/blob/master/CHANGE_LOG).
to write one see http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports).
Numba fails to infer return type of
Dict.get
orDict.setdefault
if that value (or value generated downstream) is set to theDict
.traceback
However, numba seems to be able to infer the type just fine as long as the value isn't assigned back into the dict:
Assigning the value to another dict also fails inference, but other operations I've tried (like appending to a list) seem to work fine. Additionally, if I assign a value before trying
.get
or.setdefault
, inference works.The text was updated successfully, but these errors were encountered: