Skip to content

Commit 4eaa80d

Browse files
authored
Merge pull request #307 from matthiasdiener/discard
add discard()
2 parents c9e4c4f + b89d48d commit 4eaa80d

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

docs/api/immutabledict.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
immutabledict
2-
======================
2+
=============
33

44
.. autoclass:: immutabledict.immutabledict
55
:exclude-members: items,keys,values

immutabledict/__init__.py

+15
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,21 @@ def update(self, _dict: Dict[_K, _V]) -> immutabledict[_K, _V]:
142142
new.update(_dict)
143143
return self.__class__(new)
144144

145+
def discard(self, key: _K) -> immutabledict[_K, _V]:
146+
"""
147+
Return a new :class:`immutabledict` without the item at the given key, if present.
148+
149+
:param key: the key of the item you want to remove in the returned :class:`immutabledict`
150+
151+
:return: the new :class:`immutabledict` without the item at the given
152+
key, or a reference to itself if the key is not present
153+
"""
154+
# Based on the pyrsistent.PMap.discard() API
155+
if key not in self:
156+
return self
157+
158+
return self.delete(key)
159+
145160

146161
class ImmutableOrderedDict(immutabledict[_K, _V]):
147162
"""

tests/test_immutabledict.py

+12
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,18 @@ def test_set_delete_update(self) -> None:
235235
# Make sure d doesn't change
236236
assert d == immutabledict(a=1, b=2) == dict(a=1, b=2)
237237

238+
def test_discard(self) -> None:
239+
d: immutabledict[str, int] = immutabledict(a=1, b=2)
240+
241+
# Key present
242+
assert d.discard("a") == immutabledict(b=2) == {"b": 2}
243+
assert hash(d.discard("a")) != hash(d)
244+
245+
# Key not present
246+
assert d.discard("c") == d == {"a": 1, "b": 2}
247+
assert hash(d.discard("c")) == hash(d)
248+
assert d.discard("c") is d
249+
238250
def test_new_kwargs(self) -> None:
239251
immutable_dict: immutabledict[str, int] = immutabledict(a=1, b=2)
240252
assert immutable_dict == {"a": 1, "b": 2} == dict(a=1, b=2)

0 commit comments

Comments
 (0)