python—是否可以在函数内部创建一个键类型为unituple的numba dict

63lcw9qa  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(474)

我想示例化一个麻木 Dict 在函数中,我希望键类型是三个浮点的元组。为此,a编写了以下代码:

import numba

@numba.njit
def foo():
    local_dict = numba.typed.Dict.empty(
        key_type=numba.types.UniTuple(numba.float64, 3),
        value_type=numba.float64,
    )
    return 1

if __name__ == '__main__':
    foo()

不幸的是,这段代码未能编译(错误消息如下)。
但是当我示例化 local_dict 在模块级使用完全相同的代码成功编译。
我也试着把钥匙类型改成 float64 它起了作用,表明(就像错误消息一样)问题来自 UniTuple 类型。
所以我的问题是:如何用 UniTuple 作为函数内部的键。
以下是完整的错误消息:

Traceback (most recent call last):
  File "/home/louis/PycharmProjects/Bac_a_sable/numba_sandbox.py", line 19, in <module>
    foo()
  File "/home/louis/.venvs/Bac_a_sable/lib/python3.9/site-packages/numba/core/dispatcher.py", line 420, in _compile_for_args
    error_rewrite(e, 'typing')
  File "/home/louis/.venvs/Bac_a_sable/lib/python3.9/site-packages/numba/core/dispatcher.py", line 361, in error_rewrite
    raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'UniTuple' of type Module(<module 'numba.core.types' from '/home/louis/.venvs/Bac_a_sable/lib/python3.9/site-packages/numba/core/types/__init__.py'>)

File "numba_sandbox.py", line 8:
def foo():
    <source elided>
        # key_type=numba.float64, value_type=numba.float64,
        key_type=numba.types.UniTuple(dtype=numba.float64, count=3), value_type=numba.float64,
        ^

During: typing of get attribute at /home/louis/PycharmProjects/Bac_a_sable/numba_sandbox.py (8)

File "numba_sandbox.py", line 8:
def foo():
    <source elided>
        # key_type=numba.float64, value_type=numba.float64,
        key_type=numba.types.UniTuple(dtype=numba.float64, count=3), value_type=numba.float64,
        ^

Process finished with exit code 1
c3frrgcw

c3frrgcw1#

docs声明“jit函数中不支持类型表达式”

import numba

from numba.types import UniTuple

// declare types _outside_ of function definition
value_float = numba.float64
key_float = UniTuple(numba.float64, 3)

@numba.njit
def foo():
    local_dict = numba.typed.Dict.empty(
        key_type=key_float,
        value_type=value_float
        )
    return local_dict

if __name__ == '__main__':
    print(foo()) // prints: {}

相关问题