I am trying to sort a list using a custom key within a numba-jit function in Python. Simple custom keys work, for example I know that I can just sort by the absolute value using something like this:
import numba @numba.jit(nopython=True) def myfunc(): mylist = [-4, 6, 2, 0, -1] mylist.sort(key=lambda x: abs(x)) return mylist # [0, -1, 2, -4, 6]
However, in the following more complicated example, I get an error that I do not understand.
import numba import numpy as np @numba.jit(nopython=True) def dist_from_mean(val, mu): return abs(val - mu) @numba.jit(nopython=True) def func(): l = [1,7,3,9,10,-4,-2,0] avg_val = np.array(l).mean() l.sort(key=lambda x: dist_from_mean(x, mu=avg_val)) return l
The error that it is reporting is the following:
Traceback (most recent call last): File "testitout.py", line 18, in <module> ret = func() File "/.../python3.6/site-packages/numba/core/dispatcher.py", line 415, in _compile_for_args error_rewrite(e, 'typing') File "/.../python3.6/site-packages/numba/core/dispatcher.py", line 358, in error_rewrite reraise(type(e), e, None) File "/.../python3.6/site-packages/numba/core/utils.py", line 80, in reraise raise value.with_traceback(tb) numba.core.errors.TypingError: Failed in nopython mode pipeline (step: convert make_function into JIT functions) Cannot capture the non-constant value associated with variable 'avg_val' in a function that will escape. File "testitout.py", line 14: def func(): <source elided> l.sort(key=lambda x: dist_from_mean(x, mu=avg_val)) ^
What is the appropriate way to pass in an outside value to a list sort in this case?