Skip to content

Commit 22f8b75

Browse files
committed
Fix/test KeyError in EqualityMapping, add docstring
1 parent a544741 commit 22f8b75

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

array_api_tests/dtype_helpers.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,10 +408,19 @@ def fmt_types(types: Tuple[Union[DataType, ScalarType], ...]) -> str:
408408

409409

410410
class EqualityMapping(Mapping):
411+
"""
412+
Mapping that uses equality for indexing
413+
414+
Typical mappings (e.g. the built-in dict) use hashing for indexing. This
415+
isn't ideal for the Array API, as no __hash__() method is specified for
416+
dtype objects - but __eq__() is!
417+
418+
See https://data-apis.org/array-api/latest/API_specification/data_types.html#data-type-objects
419+
"""
411420
def __init__(self, mapping: Mapping):
412421
keys = list(mapping.keys())
413422
for i, key in enumerate(keys):
414-
if not (key == key): # specifically test __eq__, not __neq__
423+
if not (key == key): # specifically checking __eq__, not __neq__
415424
raise ValueError("Key {key!r} does not have equality with itself")
416425
other_keys = keys[:]
417426
other_keys.pop(i)
@@ -424,9 +433,14 @@ def __getitem__(self, key):
424433
for k, v in self._mapping.items():
425434
if key == k:
426435
return v
436+
else:
437+
raise KeyError(f"{key!r} not found")
427438

428439
def __iter__(self):
429440
return iter(self._mapping)
430441

431442
def __len__(self):
432443
return len(self._mapping)
444+
445+
def __repr__(self):
446+
return f"EqualityMapping({self._mapping!r})"

array_api_tests/meta/test_equality_mapping.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,9 @@ def __hash__(self):
2121

2222
with pytest.raises(ValueError):
2323
EqualityMapping({AlwaysEq(0): "foo", AlwaysEq(1): "bar"})
24+
25+
26+
def test_key_error():
27+
mapping = EqualityMapping({"foo": "bar"})
28+
with pytest.raises(KeyError):
29+
mapping["nonexistent key"]

0 commit comments

Comments
 (0)