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

set update delete #7

Merged
merged 2 commits into from
Jan 24, 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
20 changes: 19 additions & 1 deletion constantdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,28 @@ def __reduce__(self) -> str | tuple[Any, ...]:
# which would raise an exception in constantdict.
return (self.__class__, (dict(self),))

def set(self, key: K, val: Any) -> constantdict[K, V]:
"""Return a new :class:`constantdict` with the item at *key* set to *val*."""
new = dict(self)
new[key] = val
return self.__class__(new)

def delete(self, key: K) -> constantdict[K, V]:
"""Return a new :class:`constantdict` without the item at the given key."""
new = dict(self)
del new[key]
return self.__class__(new)

def update(self, # type: ignore[override]
_dict: Dict[K, V]) -> constantdict[K, V]:
"""Return a new :class:`constantdict` with updated items from *_dict*."""
new = dict(self)
new.update(_dict)
return self.__class__(new)

__delitem__ = _del_attr
__setitem__ = _del_attr
clear = _del_attr
popitem = _del_attr # type: ignore[assignment]
pop = _del_attr # type: ignore[assignment]
setdefault = _del_attr # type: ignore[assignment]
update = _del_attr
23 changes: 23 additions & 0 deletions test/test_constantdict.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import Any

import pytest

from constantdict import constantdict


Expand All @@ -13,3 +15,24 @@ def test_fromkeys() -> None:
cd: constantdict[Any, Any] = constantdict.fromkeys(["a", "b", "c"])
assert cd == {"a": None, "b": None, "c": None}
assert cd == dict.fromkeys(["a", "b", "c"])


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

assert d.set("a", 10) == constantdict(a=10, b=2) == dict(a=10, b=2) # noqa: C408
assert d.delete("a") == constantdict(b=2) == dict(b=2) # noqa: C408

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

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

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

# Make sure 'd' has not changed
assert d == constantdict(a=1, b=2) == {"a": 1, "b": 2}