pythonnumpyfile-descriptorcontextmanagerresource-leak

Is NpzFile closing itself when used as a context manager?


In docstring of numpy.load() I have found the following warning:

For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors.

I noticed, that the returned NpzFile object has both __enter__() and __exit__() methods.

Would it take care of closing it automatically if i use it like this:

>>> with numpy.load('my_mile.npz') as data:
...     A = data['A']

?


Solution

  • Yes. Using a with statement will close the file-like object. Here's an example, directly from the documentation:

    with load('foo.npz') as data:
        a = data['a']