21

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
blah238
  • 35,793
  • 7
  • 94
  • 195
ustroetz
  • 7,994
  • 10
  • 72
  • 118
  • 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. –  Dec 13 '13 at 16:25

1 Answers1

22

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.

blah238
  • 35,793
  • 7
  • 94
  • 195
  • 3
    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 (http://www.python.org/dev/peps/pep-0020/). – sgillies Dec 17 '13 at 03: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 03:50
  • 3
    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
  • anyway gdal python wrapper has a design flaw, you can't rely on garbage collector to close a dataset, e.g. in pypy it would be garbaged later – sherpya Sep 27 '22 at 00:57
  • As of GDAL 3.8, the with statement is supported. – dbaston Dec 07 '23 at 15:55