Skip to content

Commit 7801758

Browse files
committed
fix(coordinate_compression): raise exceptions instead of returning -1
Previously `compress()` and `decompress()` returned -1 on invalid input while `coordinate_map[...]` raised KeyError, giving inconsistent error semantics. This change makes error handling uniform: `compress` raises KeyError and `decompress` raises IndexError, matching Python conventions and the underlying dict/list. Docstrings and doctests updated. Fixes #13509
1 parent 791deb4 commit 7801758

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

data_compression/coordinate_compression.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,21 @@ def compress(self, original: float | str) -> int:
8787
original: The value to compress.
8888
8989
Returns:
90-
The compressed integer, or -1 if not found in the original list.
90+
The compressed integer.
91+
92+
Raises:
93+
KeyError: If ``original`` was not part of the input list.
9194
9295
>>> arr = [100, 10, 52, 83]
9396
>>> cc = CoordinateCompressor(arr)
9497
>>> cc.compress(100)
9598
3
9699
>>> cc.compress(7) # Value not in the original list
97-
-1
100+
Traceback (most recent call last):
101+
...
102+
KeyError: 7
98103
"""
99-
return self.coordinate_map.get(original, -1)
104+
return self.coordinate_map[original]
100105

101106
def decompress(self, num: int) -> int | float | str:
102107
"""
@@ -108,14 +113,21 @@ def decompress(self, num: int) -> int | float | str:
108113
Returns:
109114
The original value.
110115
116+
Raises:
117+
IndexError: If ``num`` is not a valid compressed coordinate.
118+
111119
>>> arr = [100, 10, 52, 83]
112120
>>> cc = CoordinateCompressor(arr)
113121
>>> cc.decompress(0)
114122
10
115123
>>> cc.decompress(5) # Compressed coordinate out of range
116-
-1
124+
Traceback (most recent call last):
125+
...
126+
IndexError: compressed coordinate 5 is out of range
117127
"""
118-
return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1
128+
if not 0 <= num < len(self.reverse_map):
129+
raise IndexError(f"compressed coordinate {num} is out of range")
130+
return self.reverse_map[num]
119131

120132

121133
if __name__ == "__main__":

0 commit comments

Comments
 (0)