GeospatialPython / pyshp

This library reads and writes ESRI Shapefiles in pure Python.
MIT License
1.1k stars 259 forks source link

Add close method to Reader #107

Closed djhoese closed 7 years ago

djhoese commented 7 years ago

Some testing frameworks and other utilities will print a warning when files are left open at the end of a test. I've added a close method to the Reader class that closes any files that may have been opened. This close method is also called from __del__ if the Reader object is deleted/garbage collected. The warning I was getting is:

  s = shapefile.Reader(shapefilename)
my_code.py:688: ResourceWarning: unclosed file <_io.BufferedReader name='my_shape.shx'>

I'm not super familiar with the internals of Reader so there could be a chance that this could break anything returned by the Reader that references shp, shx, and dbf files and depends on them staying open.

karimbahgat commented 7 years ago

This is great and makes sense to me! I don't see any issues with it, having called close() one should only expect that it's not possible to do anything on the file anymore.

A possible extension of this would be to do the same for the Writer class, and implement __enter__ and __exit__ to allow with statements.

Thanks!