Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python type hints with numba

From the numba website:

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)?

like image 731
user308827 Avatar asked Feb 18 '17 02:02

user308827


People also ask

Is it good practice to use type hints in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

Is Numba faster than NumPy?

For the uninitiated Numba is an open-source JIT compiler that translates a subset of Python/NumPy code into an optimized machine code using the LLVM compiler library. In short Numba makes Python/NumPy code runs faster.

Do type hints slow down Python?

So in short: no, they will not cause any run-time effects, unless you explicitly make use of them. That is incorrect. They need to be resolved when loading the code and they are kept in memory. After the loading there shouldn't be slowdowns.

Does Numba work with strings?

Numba supports (Unicode) strings in Python 3. Strings can be passed into nopython mode as arguments, as well as constructed and returned from nopython mode.


1 Answers

Yes and no. You can simply use the normal python syntax for annotations (the jit decorator will preserve them). 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:

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.

like image 185
MSeifert Avatar answered Sep 21 '22 11:09

MSeifert