Skip to content

Commit 4f7587e

Browse files
committed
Fix: Ensure consistent KeyError handling for missing values in CoordinateCompressor (#13226)
1 parent 04644e1 commit 4f7587e

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

data_compression/coordinate_compression.py

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,17 +86,28 @@ def compress(self, original: float | str) -> int:
8686
Args:
8787
original: The value to compress.
8888
89+
# Returns:
90+
# The compressed integer, or -1 if not found in the original list.
91+
8992
Returns:
90-
The compressed integer, or -1 if not found in the original list.
93+
The compressed integer.
94+
95+
Raises:
96+
KeyError: If the value is not present in the original list.
9197
9298
>>> arr = [100, 10, 52, 83]
9399
>>> cc = CoordinateCompressor(arr)
94100
>>> cc.compress(100)
95101
3
96102
>>> cc.compress(7) # Value not in the original list
97-
-1
103+
Traceback (most recent call last):
104+
...
105+
KeyError: 7
98106
"""
99-
return self.coordinate_map.get(original, -1)
107+
# return self.coordinate_map.get(original, -1)
108+
if original not in self.coordinate_map:
109+
raise KeyError(original)
110+
return self.coordinate_map[original]
100111

101112
def decompress(self, num: int) -> int | float | str:
102113
"""
@@ -105,17 +116,29 @@ def decompress(self, num: int) -> int | float | str:
105116
Args:
106117
num: The compressed integer to decompress.
107118
119+
# Returns:
120+
# The original value.
121+
108122
Returns:
109-
The original value.
123+
The original value.
124+
125+
Raises:
126+
KeyError: If the compressed coordinate is out of range.
110127
111128
>>> arr = [100, 10, 52, 83]
112129
>>> cc = CoordinateCompressor(arr)
113130
>>> cc.decompress(0)
114131
10
115132
>>> cc.decompress(5) # Compressed coordinate out of range
116-
-1
133+
Traceback (most recent call last):
134+
...
135+
KeyError: 5
136+
117137
"""
118-
return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1
138+
# return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1
139+
if not 0 <= num < len(self.reverse_map):
140+
raise KeyError(num)
141+
return self.reverse_map[num]
119142

120143

121144
if __name__ == "__main__":

0 commit comments

Comments
 (0)