Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Support pickle serialization for Grid objects #46

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions gridit/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ def __hash__(self):
"""Return unique hash based on content."""
return hash(tuple(self))

def __getstate__(self):
"""Serialize object attributes for pickle dumps."""
state = dict(self)
if state["projection"] is None or state["projection"] == "":
del state["projection"]
return state

def __setstate__(self, state):
"""Set object attributes from pickle loads."""
self.__init__(**state)

def __eq__(self, other):
"""Return True if objects are equal."""
if self.__class__.__name__ != other.__class__.__name__:
Expand Down
31 changes: 31 additions & 0 deletions tests/test_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,34 @@ def test_grid_transform(grid_basic):
from affine import Affine

assert grid_basic.transform == Affine(10.0, 0.0, 1000.0, 0.0, -10.0, 2000.0)


def test_pickle():
import pickle

# Without projection
grid = Grid(25.0, (36, 33), (1748725.0, 5449775.0))
expected_bytes = (
b"\x80\x04\x95c\x00\x00\x00\x00\x00\x00\x00\x8c\x0b"
b"gridit.grid\x94\x8c\x04Grid\x94\x93\x94)\x81\x94}\x94(\x8c\n"
b"resolution\x94G@9\x00\x00\x00\x00\x00\x00\x8c\x05"
b"shape\x94K$K!\x86\x94\x8c\x08"
b"top_left\x94GA:\xae\xf5\x00\x00\x00\x00GAT\xca\x0b\xc0\x00\x00\x00\x86"
b"\x94ub."
)
assert pickle.loads(expected_bytes) == grid, "failed loading previous serialization"
assert pickle.loads(pickle.dumps(grid)) == grid, "failed round-trip"

# With projection
grid = Grid(25.0, (36, 33), (1748725.0, 5449775.0), "EPSG:2193")
expected_bytes = (
b"\x80\x04\x95|\x00\x00\x00\x00\x00\x00\x00\x8c\x0b"
b"gridit.grid\x94\x8c\x04Grid\x94\x93\x94)\x81\x94}\x94(\x8c\n"
b"resolution\x94G@9\x00\x00\x00\x00\x00\x00\x8c\x05"
b"shape\x94K$K!\x86\x94\x8c\x08"
b"top_left\x94GA:\xae\xf5\x00\x00\x00\x00GAT\xca\x0b\xc0\x00\x00\x00\x86"
b"\x94\x8c\nprojection\x94\x8c\tEPSG:2193"
b"\x94ub."
)
assert pickle.loads(expected_bytes) == grid, "failed loading previous serialization"
assert pickle.loads(pickle.dumps(grid)) == grid, "failed round-trip"
Loading