Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add discard() #307

Merged
merged 1 commit into from
Mar 6, 2024
Merged
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
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