python-3.xsignaturenumbanamedtuple

Numba namedtuple signature


I'm trying to specify the return type for a namedtuple in Numba and I am not able to do so. Could someone help? Consider the following minimal code:

import numba as nb
from   collections import namedtuple

NT = namedtuple('NT',['sum','sum2'])

@nb.njit((nb.types.NamedTuple([nb.float64,nb.float64],NT))(nb.int64,nb.float64[:,:]),fastmath=True)
def arrsum_njit(nn,xx):
    arraysum = 0.0
    out = NT(sum=arraysum,sum2=arraysum)
    return out

I get the error

No conversion from NT(float64 x 2) to NT(float64, float64) for '$20return_value.7', defined at None

File "numbanamedtuple.py", line 10:
def arrsum_njit(nn,xx):
    <source elided>
    out = NT(sum=arraysum,sum2=arraysum)
    return out
    ^

During: typing of assignment at numbanamedtuple.py (10)

File "numbanamedtuple.py", line 10:
def arrsum_njit(nn,xx):
    <source elided>
    out = NT(sum=arraysum,sum2=arraysum)
    return out

Solution

  • The problem is "overoptimized" numba compiler (bug). Add a variable of a different type to the tuple to tell the compiler to use a heterogeneous tuple (internal class).

    import numba as nb
    import numpy as np
    from collections import namedtuple
    
    NT = namedtuple('NT',['sum','sum2','dummy'])
    
    @nb.njit((nb.types.NamedTuple([nb.float64,nb.float64,nb.int64],NT))(nb.int64,nb.float64[:,:]))
    def arrsum_njit(nn,xx):
        arraysum = 0.0
        out = NT(sum=arraysum,sum2=arraysum,dummy=1)
        return out
    
    arrsum_njit(1, np.array([[1.], [2.]]))
    # >>> NT(sum=0.0, sum2=0.0, dummy=1)