GeospatialPython / pyshp

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

Fix recursion error when copying Record with deepcopy() #257

Closed midichef closed 7 months ago

midichef commented 1 year ago

This commit fixes the following error that happens when I try to do copy.deepcopy() on a Record:

Traceback (most recent call last):
  File "/home/midichef/pyshp/test.py", line 12, in <module>
    records_deepcopy = copy.deepcopy(records)
...
  File "/usr/lib/python3.8/copy.py", line 271, in _reconstruct
    if hasattr(y, '__setstate__'):
  File "/home/midichef/.local/lib/python3.8/site-packages/shapefile.py", line 735, in __getattr__
    index = self.__field_positions[item]
...
  [Previous line repeated 991 more times]
RecursionError: maximum recursion depth exceeded

The behavior can be tested with this script:

#!/usr/bin/python3

import shapefile
import copy
import pickle

shapefile_path = "shapefiles/blockgroups"
sf = shapefile.Reader(shapefile_path)
records = sf.records()

records_deepcopy = copy.deepcopy(records)
assert records_deepcopy == records

records_pickle = pickle.dumps(records)
records_unpickled = pickle.loads(records_pickle)
assert records_unpickled == records

For a good explanation of how this fix works, see this Stack Overflow comment. This commit also fixes the error previously reported when trying to unpickle records (https://github.com/GeospatialPython/pyshp/issues/238).