[Python] Numba jitclass instance array element cannot be changed based on later code

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have a numba jitclass with an instance attribute that is a 1d-array of floats, initialized to be zeros (in the MRE as [0.,0.]).

    I have a jitted function that creates an instance of said class and changes the first element of this array (in the MRE to 1, such that the array should become [1.,0.]).

    This change is not performed if the function also creates another array by copying elements from the attribute array. This happens even if the created array is empty, and even if it is created AFTER the attribute array should be changed.

    MRE:

    from numba import jit
    from numba.core import types
    from numba.experimental import jitclass
    import numpy as np



    @jitclass(spec={'attribute': types.Array(dtype=types.float64,ndim=1,layout='A')})
    class TestClass():
    def __init__(self):
    self.attribute = np.zeros(2)



    @jit
    def test_func():
    test_instance = TestClass()
    test_instance.attribute[0] = 1
    print(test_instance.attribute)



    @jit
    def test_func_bugged():
    test_instance = TestClass()
    test_instance.attribute[0] = 1
    print(test_instance.attribute)
    print(np.array([test_instance.attribute[1] for _ in range(0)]))



    test_func()
    test_func_bugged()


    Expected printed outcome:

    [1. 0.]
    [1. 0.]
    []


    Actually printed outcome:

    [1. 0.]
    [0. 0.]
    []


    I am on python-3.13.0, numba-0.61.0, and numpy-2.1.3.

    Why is this happening?

    How can one create arrays from elements of the attribute array without making its elements unchangeable?

    Continue reading...

Compartilhe esta Página