Skip to content

Commit

Permalink
add set/delete/update functions (#271)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Oct 16, 2023
1 parent bdf02ce commit 1f1f1ec
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
15 changes: 15 additions & 0 deletions immutabledict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,21 @@ def keys(self) -> KeysView[_K]:
def values(self) -> ValuesView[_V]:
return self._dict.values()

def set(self, key: _K, value: Any) -> immutabledict[_K, _V]:
new = dict(self._dict)
new[key] = value
return self.__class__(new)

def delete(self, key: _K) -> immutabledict[_K, _V]:
new = dict(self._dict)
del new[key]
return self.__class__(new)

def update(self, _dict: Dict[_K, _V]) -> immutabledict[_K, _V]:
new = dict(self._dict)
new.update(_dict)
return self.__class__(new)


class ImmutableOrderedDict(immutabledict[_K, _V]):
"""
Expand Down
18 changes: 18 additions & 0 deletions tests/test_immutabledict.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,24 @@ def test_performance(self, statement: str) -> None:

assert time_immutable < 1.2 * time_standard

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

assert d.set("a", 10) == immutabledict(a=10, b=2) == dict(a=10, b=2)
assert d.delete("a") == immutabledict(b=2) == dict(b=2)

with pytest.raises(KeyError):
d.delete("c")

assert d.update({"a": 3}) == immutabledict(a=3, b=2) == dict(a=3, b=2)

assert (
d.update({"c": 17}) == immutabledict(a=1, b=2, c=17) == dict(a=1, b=2, c=17)
)

# Make sure d doesn't change
assert d == immutabledict(a=1, b=2) == dict(a=1, b=2)

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 1f1f1ec

Please sign in to comment.