From 3d3813d2e8fbf6e55fcbf6a64a42ceb6ed6545de Mon Sep 17 00:00:00 2001 From: James Parrott <80779630+JamesParrott@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:53:30 +0000 Subject: [PATCH 1/4] Add option to possibly avoid mismatched shapes and records Update shapefile.py --- src/shapefile.py | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/shapefile.py b/src/shapefile.py index 7f32054..1364ec4 100644 --- a/src/shapefile.py +++ b/src/shapefile.py @@ -3076,7 +3076,10 @@ def __init__( ) def __len__(self) -> int: - """Returns the number of records in the .dbf file.""" + """Returns the number of records in the .dbf file + (the value declared in the header, verified + against the actual file size and other metadata). + """ return self.numRecords def _dbfHeader(self) -> None: @@ -3246,7 +3249,8 @@ def _record( namedtuples 'fieldTuples', a record name-index dict 'recLookup', and a Struct instance 'recStruct' for unpacking these fields. - None is returned for 'deleted' records (those with their deletion flag marked). + Unless 'ignore_deletion_flag' is True, None is returned for 'deleted' + records (those with their deletion flag marked). """ # The only format chars from self._record_fmt, in recStruct from _record_fields, # are s and x (ascii encoded str and pad byte) so everything in recordContents is bytes @@ -4427,6 +4431,7 @@ def iterShapeRecords( self, fields: list[str] | None = None, bbox: BBox | None = None, + _skip_shapes_with_deletion_flags_set: bool = False, ) -> Iterator[ShapeRecord]: """Returns a generator of combination geometry/attribute records for all records in a shapefile. @@ -4438,8 +4443,13 @@ def iterShapeRecords( if bbox is None: # iterate through all shapes and records for shape, record in zip( - self.iterShapes(), self.dbf_reader.iterRecords(fields=fields) + self.iterShapes(), + self.dbf_reader.iterRecords( + fields=fields, deleted_as_None=_skip_shapes_with_deletion_flags_set + ), ): + if record is None: + continue yield ShapeRecord(shape=shape, record=record) else: # Only yield ShapeRecords whose shape.bbox overlaps with bbox. @@ -4450,14 +4460,23 @@ def iterShapeRecords( if shape: if shape.oid - 1 != last_oid: self.dbf_reader.seek_to_rec(index=shape.oid) + # else we didn't skip any shapes since the last one, + # and we can avoid an extra seek. + + last_oid = shape.oid record = self.dbf_reader._record( fieldTuples=fieldTuples, recLookup=recLookup, recStruct=recStruct, oid=shape.oid, + ignore_deletion_flag=False, ) - last_oid = shape.oid + + if _skip_shapes_with_deletion_flags_set and ( + record is None or record.deletion_flag != b" " + ): + continue yield ShapeRecord(shape=shape, record=record) From c1741abf93de65e47e46fcab793921e2ab9060e4 Mon Sep 17 00:00:00 2001 From: James Parrott <80779630+JamesParrott@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:19:28 +0000 Subject: [PATCH 2/4] Revert "Add option to possibly avoid mismatched shapes and records" This reverts commit 3d3813d2e8fbf6e55fcbf6a64a42ceb6ed6545de. --- src/shapefile.py | 27 ++++----------------------- 1 file changed, 4 insertions(+), 23 deletions(-) diff --git a/src/shapefile.py b/src/shapefile.py index 1364ec4..7f32054 100644 --- a/src/shapefile.py +++ b/src/shapefile.py @@ -3076,10 +3076,7 @@ def __init__( ) def __len__(self) -> int: - """Returns the number of records in the .dbf file - (the value declared in the header, verified - against the actual file size and other metadata). - """ + """Returns the number of records in the .dbf file.""" return self.numRecords def _dbfHeader(self) -> None: @@ -3249,8 +3246,7 @@ def _record( namedtuples 'fieldTuples', a record name-index dict 'recLookup', and a Struct instance 'recStruct' for unpacking these fields. - Unless 'ignore_deletion_flag' is True, None is returned for 'deleted' - records (those with their deletion flag marked). + None is returned for 'deleted' records (those with their deletion flag marked). """ # The only format chars from self._record_fmt, in recStruct from _record_fields, # are s and x (ascii encoded str and pad byte) so everything in recordContents is bytes @@ -4431,7 +4427,6 @@ def iterShapeRecords( self, fields: list[str] | None = None, bbox: BBox | None = None, - _skip_shapes_with_deletion_flags_set: bool = False, ) -> Iterator[ShapeRecord]: """Returns a generator of combination geometry/attribute records for all records in a shapefile. @@ -4443,13 +4438,8 @@ def iterShapeRecords( if bbox is None: # iterate through all shapes and records for shape, record in zip( - self.iterShapes(), - self.dbf_reader.iterRecords( - fields=fields, deleted_as_None=_skip_shapes_with_deletion_flags_set - ), + self.iterShapes(), self.dbf_reader.iterRecords(fields=fields) ): - if record is None: - continue yield ShapeRecord(shape=shape, record=record) else: # Only yield ShapeRecords whose shape.bbox overlaps with bbox. @@ -4460,23 +4450,14 @@ def iterShapeRecords( if shape: if shape.oid - 1 != last_oid: self.dbf_reader.seek_to_rec(index=shape.oid) - # else we didn't skip any shapes since the last one, - # and we can avoid an extra seek. - - last_oid = shape.oid record = self.dbf_reader._record( fieldTuples=fieldTuples, recLookup=recLookup, recStruct=recStruct, oid=shape.oid, - ignore_deletion_flag=False, ) - - if _skip_shapes_with_deletion_flags_set and ( - record is None or record.deletion_flag != b" " - ): - continue + last_oid = shape.oid yield ShapeRecord(shape=shape, record=record) From 77d22253d5ffccabb7d1203a3986e8430d2ddc82 Mon Sep 17 00:00:00 2001 From: James Parrott <80779630+JamesParrott@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:49:40 +0000 Subject: [PATCH 3/4] Save Shape record_numbers Update shapefile.py Update README.md --- README.md | 1 + src/shapefile.py | 91 ++++++++++++++++++++++++++++----------- tests/hypothesis_tests.py | 18 ++++---- 3 files changed, 76 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index d714743..81de0dc 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,7 @@ shapeType Point do not have a bounding box 'bbox'. 'points' 'points_2D' 'points_3D' + 'record_number' 'shapeType' 'shapeTypeName' 'write_to_byte_stream' diff --git a/src/shapefile.py b/src/shapefile.py index 7f32054..96b8a1b 100644 --- a/src/shapefile.py +++ b/src/shapefile.py @@ -1216,6 +1216,7 @@ class CanHaveBboxNoLinesKwargs(TypedDict, total=False): z: Sequence[float] | None mbox: MBox | None zbox: ZBox | None + record_number: int | None class Shape: @@ -1233,6 +1234,7 @@ def __init__( bbox: BBox | None = None, mbox: MBox | None = None, zbox: ZBox | None = None, + record_number: int | None = None, ): """Stores the geometry of the different shape types specified in the Shapefile spec. Shape types are @@ -1373,6 +1375,8 @@ def __init__( elif zs_found: self.zbox = self._zbox_from_zs() + self.record_number = record_number + @property def oid(self) -> int: """The index position of the shape in the original shapefile""" @@ -1611,8 +1615,9 @@ class NullShape(Shape): def __init__( self, oid: int | None = None, + record_number: int | None = None, ): - Shape.__init__(self, shapeType=NULL, oid=oid) + Shape.__init__(self, shapeType=NULL, oid=oid, record_number=record_number) @staticmethod def from_byte_stream( @@ -1621,6 +1626,7 @@ def from_byte_stream( next_shape_pos: int, oid: int | None = None, bbox: BBox | None = None, + record_number: int | None = None, ) -> NullShape: """In the ESRI spec, Null shapes are defined in .shp files entirely by a single integer encoding shape type 0 @@ -1628,7 +1634,7 @@ def from_byte_stream( record header code). """ # Shape.__init__ sets self.points = points or [] - return NullShape(oid=oid) + return NullShape(oid=oid, record_number=record_number) @staticmethod def write_to_byte_stream( @@ -1719,10 +1725,11 @@ def from_byte_stream( next_shape_pos: int, oid: int | None = None, bbox: BBox | None = None, + record_number: int | None = None, ) -> Shape | None: ShapeClass = cast(type[_CanHaveBBox], SHAPE_CLASS_FROM_SHAPETYPE[shapeType]) - kwargs: CanHaveBboxNoLinesKwargs = {"oid": oid} # "shapeType": shapeType} + kwargs: CanHaveBboxNoLinesKwargs = {"oid": oid, "record_number": record_number} kwargs["bbox"] = shape_bbox = cls._read_bbox_from_byte_stream(b_io) # if bbox specified and no overlap, skip this shape @@ -1861,8 +1868,9 @@ def __init__( x: float, y: float, oid: int | None = None, + record_number: int | None = None, ): - Shape.__init__(self, points=[(x, y)], oid=oid) + Shape.__init__(self, points=[(x, y)], oid=oid, record_number=record_number) @staticmethod def _x_y_from_byte_stream(b_io: ReadableBinStream) -> tuple[float, float]: @@ -1889,6 +1897,7 @@ def from_byte_stream( next_shape_pos: int, oid: int | None = None, bbox: BBox | None = None, + record_number: int | None = None, ) -> Shape | None: x, y = cls._x_y_from_byte_stream(b_io) @@ -1898,7 +1907,7 @@ def from_byte_stream( if not bbox_overlap(bbox, BBox(x, y, x, y)): return None elif shapeType == POINT: - return Point(x=x, y=y, oid=oid) + return Point(x=x, y=y, oid=oid, record_number=record_number) if shapeType == POINTZ: z = PointZ._read_single_point_zs_from_byte_stream(b_io)[0] @@ -1906,9 +1915,9 @@ def from_byte_stream( m = PointM._read_single_point_ms_from_byte_stream(b_io, next_shape_pos)[0] if shapeType == POINTZ: - return PointZ(x=x, y=y, z=z, m=m, oid=oid) + return PointZ(x=x, y=y, z=z, m=m, oid=oid, record_number=record_number) - return PointM(x=x, y=y, m=m, oid=oid) + return PointM(x=x, y=y, m=m, oid=oid, record_number=record_number) # return Shape(shapeType=shapeType, points=[(x, y)], z=zs, m=ms, oid=oid) @staticmethod @@ -1919,11 +1928,11 @@ def write_to_byte_stream(b_io: WriteableBinStream, s: Shape, i: int) -> int: # Write a single Z value if s.shapeType in PointZ_shapeTypes: - n += PointZ._write_single_point_z_to_byte_stream(b_io, cast(PointZ, s), i) + n += PointZ._write_single_z_value_to_byte_stream(b_io, cast(PointZ, s), i) # Write a single M value if s.shapeType in PointM_shapeTypes: - n += PointM._write_single_point_m_to_byte_stream(b_io, cast(PointM, s), i) + n += PointM._write_single_m_value_to_byte_stream(b_io, cast(PointM, s), i) return n @@ -1940,6 +1949,7 @@ def __init__( parts: list[int] | None = None, bbox: BBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if lines: @@ -1957,6 +1967,7 @@ def __init__( parts=parts, bbox=bbox, oid=oid, + record_number=record_number, ) @@ -1972,6 +1983,7 @@ def __init__( points: PointsT | None = None, bbox: BBox | None = None, oid: int | None = None, + record_number: int | None = None, ): lines = list(args) if args else lines Shape.__init__( @@ -1981,6 +1993,7 @@ def __init__( parts=parts, bbox=bbox, oid=oid, + record_number=record_number, ) @@ -1994,6 +2007,7 @@ def __init__( points: PointsT | None = None, bbox: BBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if points: @@ -2006,10 +2020,7 @@ def __init__( ) points = list(args) Shape.__init__( - self, - points=points, - bbox=bbox, - oid=oid, + self, points=points, bbox=bbox, oid=oid, record_number=record_number ) @@ -2142,6 +2153,7 @@ def __init__( mbox: MBox | None = None, zbox: ZBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if lines: @@ -2164,6 +2176,7 @@ def __init__( zbox=zbox, mbox=mbox, oid=oid, + record_number=record_number, ) @staticmethod @@ -2189,8 +2202,11 @@ def __init__( # PyShp encodes None m values as NODATA m: float | None = None, oid: int | None = None, + record_number: int | None = None, ): - Shape.__init__(self, points=[(x, y)], m=(m,), oid=oid) + Shape.__init__( + self, points=[(x, y)], m=(m,), oid=oid, record_number=record_number + ) @staticmethod def _read_single_point_ms_from_byte_stream( @@ -2207,7 +2223,7 @@ def _read_single_point_ms_from_byte_stream( return (None,) @staticmethod - def _write_single_point_m_to_byte_stream( + def _write_single_m_value_to_byte_stream( b_io: WriteableBinStream, s: PointM, i: int ) -> int: @@ -2237,6 +2253,7 @@ def __init__( bbox: BBox | None = None, mbox: MBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if lines: @@ -2256,6 +2273,7 @@ def __init__( bbox=bbox, mbox=mbox, oid=oid, + record_number=record_number, ) @@ -2273,6 +2291,7 @@ def __init__( bbox: BBox | None = None, mbox: MBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if lines: @@ -2292,6 +2311,7 @@ def __init__( bbox=bbox, mbox=mbox, oid=oid, + record_number=record_number, ) @@ -2307,6 +2327,7 @@ def __init__( bbox: BBox | None = None, mbox: MBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if points: @@ -2325,6 +2346,7 @@ def __init__( bbox=bbox, mbox=mbox, oid=oid, + record_number=record_number, ) @@ -2339,8 +2361,11 @@ def __init__( z: float = 0.0, m: float | None = None, oid: int | None = None, + record_number: int | None = None, ): - Shape.__init__(self, points=[(x, y)], z=(z,), m=(m,), oid=oid) + Shape.__init__( + self, points=[(x, y)], z=(z,), m=(m,), oid=oid, record_number=record_number + ) # same default as in Writer._shp_record (if s.shapeType == 11:) z: Sequence[float] = (0.0,) @@ -2350,7 +2375,7 @@ def _read_single_point_zs_from_byte_stream(b_io: ReadableBinStream) -> tuple[flo return unpack(" int: # Note: missing z values are autoset to 0, but not sure if this is ideal. @@ -2379,6 +2404,7 @@ def __init__( mbox: MBox | None = None, zbox: ZBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if lines: @@ -2400,6 +2426,7 @@ def __init__( zbox=zbox, mbox=mbox, oid=oid, + record_number=record_number, ) @@ -2419,6 +2446,7 @@ def __init__( mbox: MBox | None = None, zbox: ZBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if lines: @@ -2440,6 +2468,7 @@ def __init__( mbox=mbox, zbox=zbox, oid=oid, + record_number=record_number, ) @@ -2457,6 +2486,7 @@ def __init__( mbox: MBox | None = None, zbox: ZBox | None = None, oid: int | None = None, + record_number: int | None = None, ): if args: if points: @@ -2477,6 +2507,7 @@ def __init__( zbox=zbox, mbox=mbox, oid=oid, + record_number=record_number, ) @@ -3548,7 +3579,10 @@ def shape_lengths_B(self) -> list[int]: return self._shape_lengths_B -ShapeHeaderInfoT = tuple[int, int, int] +class ShapeHeaderInfoT(NamedTuple): + offset: int + length_B: int + record_number: int class ShpReader(_HasExitStack): @@ -3610,9 +3644,9 @@ def _headers_cached_gen(self) -> Iterator[ShapeHeaderInfoT]: f" and non-positive shape record length: {recLength_16bw} (16 bit words)" ) shp_length_B = 2 * recLength_16bw - shape_header_data = header_pos, shp_length_B, recNum - self.headers_cache.append(shape_header_data) - yield shape_header_data + header_info = ShapeHeaderInfoT(header_pos, shp_length_B, recNum) + self.headers_cache.append(header_info) + yield header_info # Calculate next shape header position header_pos += 8 + shp_length_B @@ -3642,6 +3676,7 @@ def shape( offset: int | None = None, shape_len_B: int | None = None, bbox: BBox | None = None, + record_number: int | None = None, ) -> Shape | None: """Returns the Shape at a given index, or None if it is outside the specified bbox. If a corresponding .shx file is available, it @@ -3651,10 +3686,12 @@ def shape( cached in memory. """ if offset is None or shape_len_B is None: - offset, shape_len_B, _recNum = self.shape_header(index) + offset, shape_len_B, record_number = self.shape_header(index) # Seek to 8B after the offset (past the shape's 8 byte header). self.file.seek(offset + 8) - shape = self._shape(shape_len_B=shape_len_B, oid=index, bbox=bbox) + shape = self._shape( + shape_len_B=shape_len_B, oid=index, bbox=bbox, record_number=record_number + ) return shape def _shape( @@ -3662,6 +3699,7 @@ def _shape( shape_len_B: int, # Excluding header oid: int | None = None, bbox: BBox | None = None, + record_number: int | None = None, ) -> Shape | None: """Returns geometry for a single shape (or None if it is outside the specified bbox). @@ -3694,6 +3732,7 @@ def _shape( next_shape_pos=shape_len_B, oid=oid, bbox=bbox, + record_number=record_number, ) return shape @@ -3748,9 +3787,11 @@ def iterShapes( # No shx file, unknown nr of shapes # Instead iterate until reach end of file # Calculate the offset indices during iteration - for i, (pos, shape_len_B, _recNum) in enumerate(self.headers_gen()): + for i, (pos, shape_len_B, recNum) in enumerate(self.headers_gen()): self.file.seek(pos + 8) # Skip the shape's 8 byte header - shape = self._shape(shape_len_B=shape_len_B, oid=i, bbox=bbox) + shape = self._shape( + shape_len_B=shape_len_B, oid=i, bbox=bbox, record_number=recNum + ) # # pos = self.file.tell() # pos += num_bytes n += 1 diff --git a/tests/hypothesis_tests.py b/tests/hypothesis_tests.py index d5157a7..a06f0aa 100644 --- a/tests/hypothesis_tests.py +++ b/tests/hypothesis_tests.py @@ -489,20 +489,20 @@ def _assert_reader_matches_expected_shapes(r, code_ex, expected_shapes): # is not currently encoded (as we'd have to resort the entire Shapefile after each shape) assert actual.parts == expected.parts, f"{type(actual.parts)=}, {type(expected.parts)=}" - if (m := getattr(actual, "m", None)): - assert m == expected.m, f"{type(m)=}, {type(expected.m)=}" + if (m := getattr(expected, "m", None)): + assert actual.m == m, f"{type(actual.m)=}, expected {type(m)=}" else: - assert not hasattr(expected, "m") + assert not hasattr(actual, "m") - if (z := getattr(actual, "z", None)): - assert z == expected.z, f"{type(z)=}, {type(expected.z)=}" + if (z := getattr(expected, "z", None)): + assert actual.z == z, f"{type(actual.z)=}, expected {type(z)=}" else: - assert not hasattr(expected, "z") + assert not hasattr(actual, "z") - if (partTypes := getattr(actual, "partTypes", None)): - assert actual.partTypes == expected.partTypes, f"{type(actual.partTypes)=}, {type(expected.partTypes)=}" + if (partTypes := getattr(expected, "partTypes", None)): + assert actual.partTypes == partTypes, f"{type(actual.partTypes)=}, expected {type(partTypes)=}" else: - assert not hasattr(expected, "partTypes") + assert not hasattr(actual, "partTypes") @pytest.mark.hypothesis @given(codes_and_shapes=codes_and_shapes) From d4a1e9439ab77d3707cfa1fea7cfe42c7f0f7022 Mon Sep 17 00:00:00 2001 From: James Parrott <80779630+JamesParrott@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:27:19 +0000 Subject: [PATCH 4/4] v3.1.10 Read record numbers and (lazy) deletions --- README.md | 24 ++++++++++++++++-------- changelog.txt | 6 ++++++ src/shapefile.py | 2 +- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 81de0dc..437f9d6 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ The Python Shapefile Library (PyShp) reads and writes ESRI Shapefiles in pure Py - **Author**: [Joel Lawhead](https://github.com/GeospatialPython) - **Maintainers**: [James Parrott](https://github.com/JamesParrott) & [Karim Bahgat](https://github.com/karimbahgat) -- **Version**: 3.1.9 -- **Date**: 16th Nov 2026 +- **Version**: 3.1.10 +- **Date**: 29th Nov 2026 - **License**: [MIT](https://github.com/GeospatialPython/pyshp/blob/master/LICENSE.TXT) ## Contents @@ -97,16 +97,18 @@ part of your geospatial project. # Recent version Changes See also the Older version Changes section below +## 3.1.10 +### Features + - DbfReader and ShxReader can analyse deleted records and lazily deleted shapes, respectively +### Docs + - Added license, and PyPi version + downloads status badges (@fizzahussain) +### Testing + - Test fewer Python versions on MacOS due to low runner availability (highest and lowest supported CPythons only) + ## 3.1.9 ### Bug fix - Write EOF byte after .dbf file body, but only logger.info it if it's missing (PyShp has never written them until now). Raises if strict=True. -## 3.1.8 -### Internal code improvements - - Avoid unnecessary seeks in Reader.iterShapeRecords with a bbox. - - Removed lots of deletion field checks (prefer dbfReader.data_fields). - - Replace two while loops with simpler alternatives. - # The Basics @@ -1519,6 +1521,12 @@ Zac Miller # Older version changes +## 3.1.8 +### Internal code improvements + - Avoid unnecessary seeks in Reader.iterShapeRecords with a bbox. + - Removed lots of deletion field checks (prefer dbfReader.data_fields). + - Replace two while loops with simpler alternatives. + ## 3.1.7 ### Bug fix - Non-positive .shp record lengths (@lunnuyenhi-dev) and mismatched shape types now raise CorruptShpShapeRecord instead of hanging forever, raising a KeyError, or passing silently. diff --git a/changelog.txt b/changelog.txt index 5712b9e..51bba6f 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,3 +1,9 @@ +VERSION 3.1.10 +2026-11-29 + * DbfReader and ShxReader can analyse deleted records and lazily deleted shapes, respectively + * Added license, and PyPi version + downloads status badges (@fizzahussain) + * Test fewer Python versions on MacOS due to low runner availability (highest and lowest supported CPythons only) + VERSION 3.1.9 2026-11-16 * Write EOF byte after .dbf file body, but only logger.info it if it's missing (PyShp has never written them until now). Raises if strict=True. diff --git a/src/shapefile.py b/src/shapefile.py index 96b8a1b..993b8b2 100644 --- a/src/shapefile.py +++ b/src/shapefile.py @@ -8,7 +8,7 @@ from __future__ import annotations -__version__ = "3.1.9" +__version__ = "3.1.10" import array import functools