Skip to content

Commit

Permalink
set update delete
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Jan 24, 2024
1 parent 8fbd139 commit b01f64b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
19 changes: 18 additions & 1 deletion constantdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,27 @@ 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, _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
21 changes: 21 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,22 @@ 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)
assert d.delete("a") == constantdict(b=2) == dict(b=2)

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

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

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

# Make sure 'd' has not changed
assert d == constantdict(a=1, b=2) == dict(a=1, b=2)

0 comments on commit b01f64b

Please sign in to comment.