Skip to content

Commit 9214379

Browse files
authored
Copy task state without mutating its data (#721)
1 parent f08a54a commit 9214379

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

‎taskiq/state.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,7 @@ def __delattr__(self, name: str) -> None:
4141

4242
def __str__(self) -> str:
4343
return f"TaskiqState({super().__str__()})"
44+
45+
def copy(self) -> "TaskiqState":
46+
"""Return a shallow copy without changing the original state."""
47+
return self.__copy__()

‎tests/test_state.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,28 @@ def test_state_del_attr() -> None:
5656
del state.a
5757

5858
assert state.get("a") is None
59+
60+
61+
def test_state_copy() -> None:
62+
state = TaskiqState()
63+
values = [1]
64+
state.items_list = values
65+
66+
copied = state.copy()
67+
68+
assert isinstance(copied, TaskiqState)
69+
assert dict(state) == dict(copied) == {"items_list": values}
70+
assert copied["items_list"] is values
71+
copied.other = 2
72+
assert "other" not in state
73+
74+
75+
def test_state_copy_preserves_data_key() -> None:
76+
state = TaskiqState()
77+
state["data"] = "user value"
78+
79+
copied = state.copy()
80+
81+
assert dict(state) == dict(copied) == {"data": "user value"}
82+
copied["data"] = "copied value"
83+
assert state["data"] == "user value"

0 commit comments

Comments
 (0)