mathmaniage
mathmaniage

Reputation: 309

how to handle a decorator that doesn't exist

I'd like to import jit for speeding up my code, but how do I handle an error in numba is not installed on some computers? Say in the code below:

from numba import jit

@jit
def some_function(x):
    ....#some more code

now, some_function would run fine even without the decorator applied but just a bit slower. So I could put a try and except as:

try:
    from numba import jit
except:
   pass

but how do I handle this part of the code?

@jit <----- def some_function(x): ....#some more code

I could possibly maybe make something like two functions:

try:
    @jit <----
    def some_function(x):
    ...
except:
    def some_function(x):
    ...

even if this would work, it seems not good to duplicate the code.So, what is the solution to this? How do I make the decorator sort of disappear/not work if there's an import error?

Upvotes: 2

Views: 77

Answers (1)

han solo
han solo

Reputation: 6590

You could just return the function itself like,

try:
    from numba import jit
except ImportError as err:
    jit = lambda x: x # return the function itself

Upvotes: 5

Related Questions