Coroutines in numba

I am working on something that requires fast coroutines, and I believe that numba can speed up my code.

Here's a silly example: a function that squares its input and adds to it the number of times it was called.

def make_square_plus_count():
    i = 0
    def square_plus_count(x):
        nonlocal i
        i += 1
        return x**2 + i
    return square_plus_count

You can't even nopython=FalseJIT, presumably due to a keyword nonlocal.

But you don't need nonlocalto if you use a class instead:

def make_square_plus_count():
    @numba.jitclass({'i': numba.uint64})
    class State:
        def __init__(self):
            self.i = 0

    state = State()

    @numba.jit()
    def square_plus_count(x):
        state.i += 1
        return x**2 + state.i
    return square_plus_count

It at least works, but it breaks if you do nopython=True.

Is there a solution for this to be compiled with nopython=True?

+4
source share
1 answer

, ( -):

import numba

@numba.jitclass({'i': numba.uint64})
class State(object):
    def __init__(self):
        self.i = 0

    def square_plus_count(self, x):
        self.i += 1
        return x**2 + self.i

square_with_call_count = State().square_plus_count  # using the method
print([square_with_call_count(i) for i in range(10)])
# [1, 3, 7, 13, 21, 31, 43, 57, 73, 91]

, , python. , , nonlocal numpy- ( ), !

+1

Source: https://habr.com/ru/post/1667714/


All Articles