Skip to content

Commit

Permalink
Merge branch 'main' into 66-use-pipeline-for-dictupdate
Browse files Browse the repository at this point in the history
  • Loading branch information
PythonFZ authored Nov 8, 2024
2 parents 47a8560 + 04be910 commit 38edb71
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
28 changes: 28 additions & 0 deletions tests/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,31 @@ def test_dct_pop(client, request):
dct.pop("a")

assert dct.pop("a", "default") == "default"


@pytest.mark.parametrize(
"client", ["znsclient", "znsclient_w_redis", "redisclient", "empty"]
)
def test_dct_merge(client, request):
c = request.getfixturevalue(client)
if c is not None:
dct = znsocket.Dict(r=c, key="list:test")
else:
dct = {}

dct.update({"a": "1", "b": "2"})

new_dct = dct | {"b": "3", "c": "4"}

assert new_dct == {"a": "1", "b": "3", "c": "4"}
assert isinstance(new_dct, dict)

assert dct == {"a": "1", "b": "2"}

if c is not None:
dct2 = znsocket.Dict(r=c, key="list:test2")

dct2.update({"b": "3", "c": "4"})
new_dct = dct | dct2
assert new_dct == {"a": "1", "b": "3", "c": "4"}
assert isinstance(new_dct, dict)
8 changes: 8 additions & 0 deletions znsocket/objects/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ def on_refresh(self, callback: t.Callable[[RefreshDataTypeDict], None]) -> None:

self.socket.refresh_callbacks[self.key] = callback


def update(self, *args, **kwargs):
"""Update the dict with another dict or iterable."""
if len(args) > 1:
Expand Down Expand Up @@ -506,3 +507,10 @@ def update(self, *args, **kwargs):
value = f"znsocket.List:{value.key}"
pipeline.hset(self.key, key, _encode(self, value))
pipeline.execute()


def __or__(self, value: "dict|Dict") -> dict:
if isinstance(value, Dict):
value = dict(value)
return dict(self) | value

0 comments on commit 38edb71

Please sign in to comment.