netcdf4-python icon indicating copy to clipboard operation
netcdf4-python copied to clipboard

Closing Dataset raises Exception on access to locals() and globals()

Open AvlWx2014 opened this issue 8 years ago • 1 comments

Opening a Dataset, and then subsequently closing it causes later access to locals() or globals() to raise RuntimeError: NetCDF: Not a valid ID. This occurs when a with block goes out of scope or if the close() method of a Dataset object is called explicitly. Raising this exception so that client code that tries to access a closed Dataset is valid functionality, but it shouldn't break Python builtins. In order to get globals() and locals() to not raise an exception, one has to "garbage collect" (so to speak) the closed Dataset themselves by calling del <identifier> so as to remove and its value from globals() and locals().

In case anyone would like to try it:

from netCDF4 import Dataset

# open a test dataset, create a dimension, and let 
# the context manager close it
with Dataset("test.nc", "w") as nc:
    nc.createDimension("test", None)

# try to access globals()
globals()

# try to access locals()
# if this code is run in a script, you shouldn't make it here
# line-by-line, though, you can use this
# it will also raise the Exception
locals()

# explicitly "garbage collect" it
del nc

globals()
locals()

AvlWx2014 avatar Aug 04 '17 11:08 AvlWx2014

Can't reproduce this on my desktop mac. What version of netcdf are you using? Try running this and report the output here:

import netCDF4, sys, numpy
sys.stdout.write('netcdf4-python version: %s\n'%netCDF4.__version__)
sys.stdout.write('HDF5 lib version:       %s\n'%netCDF4.__hdf5libversion__)
sys.stdout.write('netcdf lib version:     %s\n'%netCDF4.__netcdf4libversion__)
sys.stdout.write('numpy version           %s\n' % numpy.__version__)

I get

netcdf4-python version: 1.3.0
HDF5 lib version:       1.10.0
netcdf lib version:     4.4.1
numpy version           1.12.1

jswhit avatar Aug 12 '17 15:08 jswhit