17

I see quite often in Python GDAL code that people close datasets at the end of their script. Why does it makes sense to close a dataset in Python GDAL? Are there any consequences if I don't do it?

import gdal

# open dataset
ds = gdal.Open('test.tif')

# close dataset
ds = None
  • Sometimes the C++ destructor does things other than clean up(for some drivers), such as recomputing statistics. It's good practice to set to None, everything blah238 says is correct as well AFAIK. – user10353 Dec 13 '13 at 16:25
15

I do not think this has any purpose at the end of the script, as the Python garbage collector will do the same thing automatically when the script exits. The reason you might want to do it is in the middle of your script, to recover the resources held by accessing the dataset, remove file locks, etc. so that you can reuse them.

del ds should have the same effect but is more clear as to its intent.

The more Pythonic approach would be to use a with statement, but GDAL/OGR does not implement it. However, there are some GDAL/OGR wrappers like Rasterio and Fiona that do.

  • 2
    Consider Python file objects. You open one with f = open(filename) and you close one with f.close(). Not del f or f = None. Why? Because what happens to objects after they are no longer referenced is a detail of the interpreter's implementation and because explicit is better than implicit (python.org/dev/peps/pep-0020). – sgillies Dec 17 '13 at 3:34
  • 1
    Agreed, but the GDAL Python bindings aren't exactly Pythonic. There is a GDALClose() method that should be called if you want to be explicit (I see that Rasterio calls this internally). – blah238 Dec 17 '13 at 3:50
  • 2
    In Python, GDALClose() has not been implemented but setting the dataset to None (i.e., ds = None) is equivalent. – Arthur Jan 30 '15 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.