Skip to content

Commit

Permalink
add set/delete/update functions
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Oct 6, 2023
1 parent 55c6a31 commit fcf56ed
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 @@ -94,6 +94,21 @@ def keys(self) -> KeysView[_K]:
def values(self) -> ValuesView[_V]:
return self._dict.values()

def set(self, _key: _K, _value: _V) -> 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 @@ -211,6 +211,24 @@ def test_performance(self, statement: str) -> None:

assert time_immutable < 1.2 * time_standard

def test_set_delete_update(self) -> None:
d = 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)


class TestImmutableOrderedDict:
def test_ordered(self) -> None:
Expand Down

0 comments on commit fcf56ed

Please sign in to comment.