Skip to content

Build and run agents you can see, understand and trust.

fix(utils): make DictMixin honor missing-attribute semantics (#2241)

Diao Cepengf41cb770ae4d
diff --git a/src/agentscope/_utils/_mixin.py b/src/agentscope/_utils/_mixin.py
index 1ead2b641..0605803a1 100644
--- a/src/agentscope/_utils/_mixin.py
+++ b/src/agentscope/_utils/_mixin.py
@@ -6,4 +6,23 @@ class DictMixin(dict):
"""The dictionary mixin that allows attribute-style access."""
__setattr__ = dict.__setitem__
- __getattr__ = dict.__getitem__
+
+ def __getattr__(self, key: str) -> object:
+ """Get a dictionary item through attribute-style access.
+
+ Args:
+ key (`str`):
+ The requested attribute name.
+
+ Returns:
+ `object`:
+ The value stored under ``key``.
+
+ Raises:
+ `AttributeError`:
+ If the dictionary does not contain ``key``.
+ """
+ try:
+ return dict.__getitem__(self, key)
+ except KeyError as error:
+ raise AttributeError(key) from error
diff --git a/tests/mixin_test.py b/tests/mixin_test.py
new file mode 100644
index 000000000..98d7141f0
--- /dev/null
+++ b/tests/mixin_test.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+"""Unit tests for dictionary-backed response attribute access."""
+from copy import deepcopy
+from unittest import TestCase
+
+from agentscope.message import TextBlock
+from agentscope.model import ChatResponse
+
+
+class DictMixinTest(TestCase):
+ """Test response behavior provided by ``DictMixin``."""
+
+ def test_chat_response_can_be_deep_copied(self) -> None:
+ """A chat response can be copied without sharing mutable fields."""
+ response = ChatResponse(
+ content=[TextBlock(text="hello")],
+ is_last=True,
+ )
+
+ copied = deepcopy(response)
+
+ self.assertEqual(copied, response)
+ self.assertIsNot(copied, response)
+ self.assertIsNot(copied.content, response.content)
+ self.assertIsNot(copied.content[0], response.content[0])
+
+ def test_missing_attributes_follow_attribute_protocol(self) -> None:
+ """Missing attributes use normal Python attribute semantics."""
+ response = ChatResponse(content=[], is_last=True)
+
+ self.assertFalse(hasattr(response, "missing"))
+ self.assertEqual(
+ getattr(response, "missing", "fallback"),
+ "fallback",
+ )
+ with self.assertRaises(AttributeError):
+ getattr(response, "missing")
+
+ with self.assertRaises(KeyError):
+ _ = response["missing"]