From 0b98057046441b46ff4d30b6d7728f70f4747f95 Mon Sep 17 00:00:00 2001 From: Christian Ledermann Date: Sat, 28 Oct 2023 20:18:09 +0100 Subject: [PATCH] Make geometry collections hashable --- docs/HISTORY.txt | 1 + pygeoif/geometry.py | 4 ++++ tests/test_geometrycollection.py | 18 +++++++++++++----- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/HISTORY.txt b/docs/HISTORY.txt index 29c6ae33..b347f272 100644 --- a/docs/HISTORY.txt +++ b/docs/HISTORY.txt @@ -5,6 +5,7 @@ Changelog ------------------ - remove Python 3.7 support + - Geometries are now immutable and hashable 1.1.1 (2023/10/27) ------------------ diff --git a/pygeoif/geometry.py b/pygeoif/geometry.py index ee259e05..8ea35cc3 100644 --- a/pygeoif/geometry.py +++ b/pygeoif/geometry.py @@ -1110,6 +1110,10 @@ def __eq__(self, other: object) -> bool: second=other.__geo_interface__, # type: ignore [attr-defined] ) + def __hash__(self) -> int: + """Return the hash of the collection.""" + return hash(self.wkt) + def __len__(self) -> int: """ Length of the collection. diff --git a/tests/test_geometrycollection.py b/tests/test_geometrycollection.py index a0bccc78..27915bf0 100644 --- a/tests/test_geometrycollection.py +++ b/tests/test_geometrycollection.py @@ -1,7 +1,5 @@ """Test Baseclass.""" -import pytest - from pygeoif import geometry @@ -429,7 +427,6 @@ def test_nested_geometry_collection_repr_eval() -> None: ) -@pytest.mark.xfail(reason="GeometryCollection is not hashable") def test_nested_geometry_collection_hash() -> None: multipoint = geometry.MultiPoint([(0, 0), (1, 1), (1, 2), (2, 2)]) gc1 = geometry.GeometryCollection([geometry.Point(0, 0), multipoint]) @@ -445,10 +442,21 @@ def test_nested_geometry_collection_hash() -> None: line = geometry.LineString([(0, 0), (1, 1)]) gc = geometry.GeometryCollection([gc2, poly1, poly2, p0, p1, ring, line]) - assert hash(gc) == 0 + assert hash(gc) == hash( + geometry.GeometryCollection( + [ + gc2, + poly1, + poly2, + p0, + p1, + ring, + line, + ], + ), + ) -@pytest.mark.xfail(reason="GeometryCollection is not hashable") def test_hash_empty() -> None: gc = geometry.GeometryCollection([])