Skip to content

Commit

Permalink
Avoid over-eager KeyError on empty dict.pop
Browse files Browse the repository at this point in the history
  • Loading branch information
pschanely committed Mar 15, 2024
1 parent 7b592f5 commit 24aa9d1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
23 changes: 12 additions & 11 deletions crosshair/simplestructs.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,17 +243,18 @@ def _lastitem(self):
def pop(self, key, default=_MISSING):
# CPython checks the empty case before attempting to hash the key.
# So this must happen before the hash-ability check:
if self._len == 0:
raise KeyError
try:
value = self[key]
except KeyError:
if default is _MISSING:
raise
return default
else:
del self[key]
return value
if self._len > 0:
try:
value = self[key]
except KeyError:
pass
else:
del self[key]
return value
# Not found:
if default is _MISSING:
raise
return default

def popitem(self):
for key in self._reversed():
Expand Down
7 changes: 7 additions & 0 deletions crosshair/simplestructs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ def test_ShellMutableMap_popitem_ordering() -> None:
assert SimpleDict([("c", "d"), ("a", "b")]).popitem() == ("a", "b")


def test_ShellMutableMap_pop_with_default() -> None:
assert {"c": "d", "a": "b"}.popitem() == ("a", "b")
assert ShellMutableMap({}).pop("a", "x") == "x"
assert ShellMutableMap({"a": "b"}).pop("a", "x") == "b"
assert ShellMutableMap({"a": "b"}).pop("c", "x") == "x"


def test_ShellMutableMap_poo() -> None:
m = ShellMutableMap({2: 0})
assert 0 == m.setdefault(2.0, {True: "0"})
Expand Down

0 comments on commit 24aa9d1

Please sign in to comment.