2

Is it possible to use the Python "with" statement with the ogr.open(file) function?

For example, I would like to do something like:

with ogr.open(file) as ds:

At the moment, I can only get the following to work:

try:
    ds = ogr.open(file)
    ...

except:
    del ds
Philip Whitten
  • 293
  • 2
  • 16
  • What do you expect to do with `with` ? Call `ds.close()` at the end ? – UltraInstinct Jun 23 '16 at 03:04
  • The ds (DataSource) object does not have a close() attribute. Without using a try - finally combination (or try - except) I find that my interpreter keeps a lock on the opened ds (DataSource) even if I have the "del ds" in the script. – Philip Whitten Jun 23 '16 at 09:49

1 Answers1

4

According to the documentation, it appears that you cannot use with ogr.Open(file) ...

A Python object that you use in a with statement needs to have methods __enter__ and __exit__ to set up and take down a context used inside the with block. Here's an explanation.

According to the Documentation for OGR Open, these __enter__ and __exit__ methods are not defined for the DataSource object returned by Open so you cannot use the result from ogr.Open as the subject of a with statement.

So it looks like you'll have to use your try/except combination (although a try/finally combination might be better).

Peter Raynham
  • 647
  • 3
  • 6
  • Thank you, your explanation helps me to understand why I can't use it. It would help preventing software from keeping lock's on files after a script has been executed. – Philip Whitten Jun 23 '16 at 09:41