Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions portion/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from .const import Bound
from .interval import Interval

_MISSING = object() # Sentinel to distinguish "no default" from "default=None"


def _sortkey(i):
# Sort by lower bound, closed first
Expand Down Expand Up @@ -149,20 +151,20 @@ def domain(self):
"""
return self._klass(*self._storage.keys())

def pop(self, key, default=None):
def pop(self, key, default=_MISSING):
"""
Remove key and return the corresponding value if key is not an Interval.
If key is an interval, it returns an IntervalDict instance.

This method combines self[key] and del self[key]. If a default value
is provided and is not None, it uses self.get(key, default) instead of
self[key].
is provided, it uses self.get(key, default) instead of self[key],
which means missing keys return the default rather than raising KeyError.

:param key: a single value or an Interval instance.
:param default: optional default value.
:return: an IntervalDict, or a single value if key is not an Interval.
"""
if default is None:
if default is _MISSING:
value = self[key]
del self[key]
return value
Expand Down
4 changes: 4 additions & 0 deletions tests/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,10 @@ def test_pop_missing_value(self):
t = d.pop(4, 1)
assert t == 1

# None as explicit default must be returned, not treated as "no default"
t = d.pop(4, None)
assert t is None

def test_pop_interval(self):
d = P.IntervalDict([(P.closed(0, 3), 0)])
t = d.pop(P.closed(0, 1))
Expand Down