How to distribute Python package with Numba as optional dependency

Viewed 100

Given a numba-decorated code,

from numba import jit

@jit(nopython=True)
def f():
    ...

, how does one distribute this as a package with Numba as an optional dependency? For example, I want to install my package via pip install mypackage[jit] that includes numba and removing the extra tag excludes numba.

A bad answer is one that requires user to install Numba and, for example, set NUMBA_DISABLE_JIT=1.

2 Answers

Create a dummy decorator:

try:
    from numba import jit
except ImportError:
    def jit(*args, **kwargs):
        return lambda f: f


@jit(nopython=True)
def f():
    ...

A solution, albeit not pretty...

USE_NUMBA = True
try:
    from numba import jit
except ImportError:
    USE_NUMBA = False

def f():
    ...

if USE_NUMBA:
    f = jit(nopython=True)(f)

Related