Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type infer error on seemingly simple class method

During running (numba compilation) of the following class method:

@jit(nopython=True)
def isInPosition(self):
    """Returns whether the axis is in the desired position."""
    return True if self.state & 0x04 else False

I receive a type infer error message:

cannot determine Numba type of class X.X

How can I make it work?

like image 733
Lazac Avatar asked Nov 24 '25 12:11

Lazac


1 Answers

If you're in nopython mode each variable's type must be supported by numba. Non-static-methods in Python take a self argument and as long as you're not using a jitclass then the type of self isn't supported in nopython mode which makes it impossible to jit it like that.

However you could refactor it in an unjitted method and a jitted function:

import numba as nb

@nb.njit
def _is_in_position(state):
    return bool(state & 0x04)

class Fun:
    def __init__(self, state):
        self.state = state

    def is_in_position(self):
        return _is_in_position(self.state)

You could also check if it's faster if you jit the method in object mode, maybe it can inline the inner function call:

import numba as nb

@nb.njit
def _is_in_position(state):
    return bool(state & 0x04)

class Fun:
    def __init__(self, state):
        self.state = state

    @nb.jit
    def is_in_position(self):
        return _is_in_position(self.state)

Depending on the class it could be possible to make it a jitclass (but jitclass requires everything to be typed with supported types so it's likely that you cannot do that):

import numba as nb

spec = [
    ('state', nb.int64),
]

@nb.jitclass(spec)
class Fun(object):
    def __init__(self, state):
        self.state = state

    def is_in_position(self):
        return bool(self.state & 0x04)
like image 101
MSeifert Avatar answered Nov 27 '25 01:11

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!