简体   繁体   English

使用带有numba的python类型提示

[英]Using python type hints with numba

From the numba website: 来自numba网站:

from numba import jit

@jit
def f(x, y):
    # A somewhat trivial example
    return x + y

Is there a way to have numba use python type hints (if provided)? 有没有办法让numba使用python类型提示(如果提供)?

Yes and no. 是的,不是。 You can simply use the normal python syntax for annotations (the jit decorator will preserve them). 您可以简单地使用普通的python语法进行注释( jit装饰器将保留它们)。 Building on your simple example: 基于您的简单示例:

from numba import jit

@jit
def f(x: int, y: int) -> int:
    # A somewhat trivial example
    return x + y

>>> f.__annotations__
{'return': int, 'x': int, 'y': int}
>>> f.signatures  # they are not recognized as signatures for jit
[]

However to explicitly (enforce) the signature it must be given in the jit -decorator: 但是要明确(强制执行)签名,必须在jit -decorator中给出:

from numba import int_

@jit(int_(int_, int_))
def f(x: int, y: int) -> int:
    # A somewhat trivial example
    return x + y

>>> f.signatures
[(int32, int32)]  # may be different on other machines

There is as far as I know no automatic way for jit to understand the annotations and build its signature from these. 据我所知, jit没有自动的方式来理解注释并从中构建它的签名。

Since it is Just In Time compilation, you must execute the function to generate the signatures 由于它是即时编译,您必须执行该功能以生成签名

In [119]: f(1.0,1.0)
Out[119]: 2.0

In [120]: f(1j,1)
Out[120]: (1+1j)

In [121]: f.signatures
Out[121]: [(float64, float64), (complex128, int64)]

A new signature is generated each time the previous doesn't fit the data. 每次前一个不符合数据时,都会生成一个新签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM