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 set/delete/update functions #271

Merged
merged 2 commits into from
Oct 16, 2023
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
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