What is the best way to generate an implementation of a function at compile time?

To implement some functions (eg. einsum), the esiest way may be to generate the code at compile time. For this example I reimplemented np.sum (axis can only be literals or a tuple of literals).

  • Are there better ways to generate code at compile time (eg. without using exec)?
  • Why is Numba so slow when using the axis parameter?


import numpy as np
import numba as nb
from numba.extending import overload

def gen_sum_impl(arr_dim,c_contiguous,f_contiguous,axis=None):
    s="import numpy as np\n"
    s+="def sum_impl(arr,axis=None):\n"
    #Check for axis <0
    if axis is not None:
        if isinstance(axis, tuple):
    #handle fortran ordered arrays
    if f_contiguous:
        s+="    arr=arr.T\n"
        if axis is not None:
    alloc_axis = np.setdiff1d(np.arange(arr_dim),axis)
    #Check for illegal axis and illegal axis 
    #and if sum is performed over last axis
    if axis is not None:
        if np.max(axis)>=arr_dim:
            print("Axis is higher than array dimension!")
        if isinstance(axis, int):
            if axis==(arr_dim-1):
            if (arr_dim-1) in axis:
    #preallocating output
    if axis is None:
        s+="    res=0\n"
        s_alloc=str().join("arr.shape["+str(i)+"]," for i in alloc_axis)
        s+="    res=np.zeros(("+s_alloc+"),dtype=arr.dtype)\n"
    #avoid nested loops on contiguous arrays
    if axis is None and (c_contiguous or f_contiguous):
        s+="    arr=arr.reshape(-1)\n"
        s+="    for i_0 in range(arr.shape[0]):\n"
        s+="        res+=arr[i_0]\n"
    #nested loops
        s_lhs=str().join("i_"+str(i)+"," for i in alloc_axis)[:-1]
        s_rhs=str().join("i_"+str(i)+"," for i in np.arange(arr_dim))[:-1]
        #Special implementation if last dim is summed up (performance)
        if last_axis_contract:
            for i in range(arr_dim-1):
                s+="    "*(i+1)+"for i_"+str(i)+" in range(arr.shape["+str(i)+"]):\n"
            s+="    "*(arr_dim)+"acc=0\n"
            s+="    "*(arr_dim)+"for i_"+str(arr_dim-1)+" in range(arr.shape["+str(arr_dim-1)+"]):\n"
            s+="    "*(arr_dim+1)+"acc += arr["+s_rhs+"]\n"
            s+="    "*(arr_dim)+"res["+s_lhs+"] += acc\n"
            for i in range(arr_dim):
                s+="    "*(i+1)+"for i_"+str(i)+" in range(arr.shape["+str(i)+"]):\n"

            s+="    "*(arr_dim+1)+"res["+s_lhs+"] += arr["+s_rhs+"]\n"
    if f_contiguous and axis is not None:
        s+="    return res.T"
        s+="    return res"
    return s

def exec_func(func_str,function_name=None):
    dict_func = {}
    exec(func_str, dict_func)
    if function_name==None:
    return dict_func[function_name]

def sum_2(arr,axis=None):
    return np.sum(arr,axis)

def sum(arr, axis=None):
    axis can only be zero, a literal or a tuple of int literals
    if axis is not None and  not isinstance(axis,nb.core.types.misc.NoneType):
        if isinstance(axis,nb.core.types.containers.Tuple):
            axis_TMP=[ax.literal_value for ax in axis]
    return func


def nb_sum(arr):
    return np.sum(arr)

def nb_sum_2(arr):
    return sum_2(arr,axis=(2,3)

%timeit np.sum(arr,axis=-1)
#21.6 ms ± 301 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit nb_sum(arr)
#367 ms ± 8.55 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit nb_sum_2(arr)
#16.9 ms ± 136 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit np.sum(arr,axis=-1)
#23.5 ms ± 435 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit nb_sum(arr)
#139 ms ± 333 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit nb_sum_2(arr)
#22 ms ± 232 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit np.sum(arr,axis=(2,3))
#37.2 ms ± 303 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
#%timeit nb_sum(arr)
#not supported
%timeit nb_sum_2(arr)
#15.3 ms ± 127 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Although in your case since you’re overloading you’re achieving roughly the same thing.I haven’t 100% read through your code, but something I usually do in these situations is write an njitted function for any behavior that is shared between implementations and then return a dynamically generated function (via python, usually not strings) for each type.

Also if you must generate your code via building strings (sometimes this is the only option, but there are usually others), I often find that this https://realpython.com/python-f-strings/ is much cleaner than concatenating each line.

Other performance tip. If you use np.empty() instead of np.zeros() you can shave off some time. Just be careful that you don’t leave any slots unfilled or they could take unpredictable values.