Error while slicing an array

I welcome everyone!
When using Numba, an error occurs in the following code

import numpy as np
from numba import njit

height=10
width=5

image = np.zeros((height, width), np.int32)

@njit
def UpdateStatus():
global image, width, height
image[1:height-1, 1:width-1] = 1

UpdateStatus()
print(image)

Error: “NumbaTypeError: Cannot modify array of type: readonly array(int32, 2D, C)”.
The error is caused by the line “image[1:height-1, 1:width-1] = 1”.

It’s just that this code works in Python.

What needs to be corrected to remove the error?

Thank you.

Welcome! As the error already hints at, the array (image) you’re trying to change is readonly. That’s because you defined it as a global variable.

You can avoid it by passing the array as an argument to the function, which is arguably better practice regardless of the error.

For example:

import numpy as np
from numba import njit

@njit
def UpdateStatus(image):
    height, width = image.shape
    image[1:height-1, 1:width-1] = 1

height=10
width=5
image = np.zeros((height, width), np.int32)

UpdateStatus(image)
print(image)

Shows:

array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])

You can of course also add the height and width as arguments, instead of retrieving them from the image within the function. Both probably come with their own (small) performance overhead (arguments vs shape attribute/method), I would go with easy/flexible for starters.

Note that in this specific example, you can also avoid the height and width entirely by using a negative index (starting from the “end” of the array, whatever it is). This can be done with image[1:-1, 1:-1] = 1 which should give the exact same result in this case.

Thank you for your detailed answer and advice on code optimization.
Everything is working.