Search code examples
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
    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[:,:]),fastmath=True)
    def arrsum_njit(nn,xx):
        arraysum = 0.0
        out = NT(sum=arraysum,sum2=arraysum,dummy=1)
        return out
    

    Upd: Tested:

    • Numba 0.51.2/ Windows
    • Numba 0.48.0/ Google colab - Linux Ubuntu 18.04.5 LTS