Skip to content

Commit

Permalink
add discard()
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Mar 5, 2024
1 parent c9e4c4f commit b89d48d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/api/immutabledict.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
immutabledict
======================
=============

.. autoclass:: immutabledict.immutabledict
:exclude-members: items,keys,values
Expand Down
15 changes: 15 additions & 0 deletions immutabledict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,21 @@ def update(self, _dict: Dict[_K, _V]) -> immutabledict[_K, _V]:
new.update(_dict)
return self.__class__(new)

def discard(self, key: _K) -> immutabledict[_K, _V]:
"""
Return a new :class:`immutabledict` without the item at the given key, if present.
:param key: the key of the item you want to remove in the returned :class:`immutabledict`
:return: the new :class:`immutabledict` without the item at the given
key, or a reference to itself if the key is not present
"""
# Based on the pyrsistent.PMap.discard() API
if key not in self:
return self

return self.delete(key)


class ImmutableOrderedDict(immutabledict[_K, _V]):
"""
Expand Down
12 changes: 12 additions & 0 deletions tests/test_immutabledict.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,18 @@ def test_set_delete_update(self) -> None:
# Make sure d doesn't change
assert d == immutabledict(a=1, b=2) == dict(a=1, b=2)

def test_discard(self) -> None:
d: immutabledict[str, int] = immutabledict(a=1, b=2)

# Key present
assert d.discard("a") == immutabledict(b=2) == {"b": 2}
assert hash(d.discard("a")) != hash(d)

# Key not present
assert d.discard("c") == d == {"a": 1, "b": 2}
assert hash(d.discard("c")) == hash(d)
assert d.discard("c") is d

def test_new_kwargs(self) -> None:
immutable_dict: immutabledict[str, int] = immutabledict(a=1, b=2)
assert immutable_dict == {"a": 1, "b": 2} == dict(a=1, b=2)
Expand Down

0 comments on commit b89d48d

Please sign in to comment.