numpy - reason to use 'with' for np.nditer

numpy - reason to use 'with' for np.nditer,numpy,Numpy,Please explain if tbere is a reason of using with for the nditer as shown in the NumPy document numpy.nditer. It is to understand if there is a necessity that we have to use 'with' when using nditer. In my understanding, 'with' is to make sure a resource (e.g. open file descriptor) gets released. I am not sure what resource is to be released in the code. def iter_add_py(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonl

Please explain if tbere is a reason of using

with
for the
nditer
as shown in the NumPy document numpy.nditer.

It is to understand if there is a necessity that we have to use 'with' when using nditer. In my understanding, 'with' is to make sure a resource (e.g. open file descriptor) gets released. I am not sure what resource is to be released in the code.

def iter_add_py(x, y, out=None):
    addop = np.add
    it = np.nditer([x, y, out], [],
                [['readonly'], ['readonly'], ['writeonly','allocate']])
    with it:     # <-----
        for (a, b, c) in it:
            addop(a, b, out=c)
    return it.operands[2]

Update

As pointed out, the Iterating Over Arrays - Modifying Array Values says:

because the nditer must copy this buffer data back to the original array once iteration is finished, you must signal when the iteration is ended, by one of two methods. You may either:

  • use the nditer as a context manager using the with statement, and the temporary data will be written back when the context is exited.

  • call the iterator’s close method once finished iterating, which will trigger the write-back.


#1

What is the actual question and what do you expect this code to do? It is a bit unclear (so please edit the question).

#2

@JérômeRichard, the code itself is from the numpy documentation, and the question is about 'with', if there is a compelling reason that with needs to be used in the code.

#3

The docs also say: "To get started using this object, see the introductory guide to array iteration." You should read the introductory guide.

#4

@myrtlecat, thanks for the pointer. Indeed.

#5

Beware that unless you port your code to cython as described at the end of the intro, you probably won't see performance improvements,