使用 Numba 时如何指定“字符串”数据类型?

Yun*_*Wei 8 python string numba

Numba 无法识别该字符串。我该如何更正以下代码?谢谢你!

@nb.jit(nb.float64(nb.float64[:], nb.char[:]), nopython=True, cache=True)
def func(x, y='cont'):
    """
    :param x: is np.array, x.shape=(n,)
    :param y: is a string, 
    :return: a np.array of same shape as x
    """
    return result
Run Code Online (Sandbox Code Playgroud)

Jos*_*del 6

以下适用于 Numba 0.44:

import numpy as np
import numba as nb

from numba import types

@nb.jit(nb.float64[:](nb.float64[:], types.unicode_type), nopython=True, cache=True)
def func(x, y='cont'):
    """
    :param x: is np.array, x.shape=(n,)
    :param y: is a string, 
    :return: a np.array of same shape as x
    """
    print(y)
    return x
Run Code Online (Sandbox Code Playgroud)

func但是,如果您尝试在没有指定值的情况下运行,您将会收到错误y,因为在您的签名中您说第二个参数是必需的。我尝试弄清楚如何处理可选参数(查看types.Omitted),但不太明白。我可能会考虑不指定签名并让 numba 进行正确的类型推断:

@nb.jit(nopython=True, cache=True)
def func2(x, y='cont'):
    """
    :param x: is np.array, x.shape=(n,)
    :param y: is a string, 
    :return: a np.array of same shape as x
    """
    print(y)
    return x
Run Code Online (Sandbox Code Playgroud)