fix: raise AttributeError instead of KeyError in __getattr__#123
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates the getattr method in dashscope/api_entities/dashscope_response.py to handle missing keys by raising an AttributeError instead of a KeyError. The reviewer suggests enhancing the error message to include the class name, which would improve debugging clarity and align with standard Python error reporting.
| try: | ||
| return self[attr] | ||
| except KeyError: | ||
| raise AttributeError(attr) from None |
There was a problem hiding this comment.
While raising AttributeError correctly fixes the reported issue, the error message could be improved to follow standard Python conventions. Currently, it only provides the attribute name, which results in a terse error like AttributeError: missing_attr. A more descriptive message including the class name (e.g., AttributeError: 'DashScopeAPIResponse' object has no attribute 'missing_attr') would be more helpful for debugging and consistent with built-in Python behavior.
| raise AttributeError(attr) from None | |
| raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'") from None |
Fixed the bug described in issue #114. Here's what was wrong and how I fixed it:
Problem
DashScopeAPIResponse.getattr raised KeyError when an attribute was missing, but Python's attribute-access protocol requires AttributeError. This broke common Python patterns like getattr(obj, name, default) and hasattr(obj, name) — both rely on AttributeError to trigger the default/fallback path.
Fix
Changed getattr in dashscope/api_entities/dashscope_response.py to catch the KeyError and re-raise it as AttributeError:
Tested by
All 4 test cases pass:
Fixes: #114