-
Notifications
You must be signed in to change notification settings - Fork 18
Open
Description
Bug
DashScopeAPIResponse.__getattr__ (line 62 of dashscope/api_entities/dashscope_response.py) raises KeyError when an attribute is missing, but Python's attribute-access protocol expects AttributeError.
# Current code
def __getattr__(self, attr):
return self[attr] # raises KeyError if attr is missingImpact
This breaks two common Python patterns:
# Both of these fail because KeyError is raised instead of AttributeError
getattr(response.output, "reasoning_content", None) # KeyError instead of returning None
hasattr(response.output, "reasoning_content") # KeyError instead of returning Falsegetattr(obj, name, default) and hasattr(obj, name) both rely on AttributeError to trigger the default/fallback path. A KeyError propagates as an unhandled exception.
Suggested Fix
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError(attr) from NoneReferences
- Python data model —
__getattr__: "Called when the default attribute access fails withAttributeError" - Built-in
getattr: "If the named attribute does not exist, default is returned if provided, otherwiseAttributeErroris raised."
中文说明
问题描述
DashScopeAPIResponse.__getattr__(位于 dashscope/api_entities/dashscope_response.py 第 62 行)在属性不存在时抛出 KeyError,但 Python 的属性访问协议要求抛出 AttributeError。
# 当前代码
def __getattr__(self, attr):
return self[attr] # 属性不存在时抛出 KeyError影响
这会导致两种常见的 Python 用法失效:
# 以下两种写法都会失败,因为抛出的是 KeyError 而非 AttributeError
getattr(response.output, "reasoning_content", None) # 抛出 KeyError,而非返回 None
hasattr(response.output, "reasoning_content") # 抛出 KeyError,而非返回 Falsegetattr(obj, name, default) 和 hasattr(obj, name) 都依赖 AttributeError 来触发默认值/回退逻辑。KeyError 会作为未处理的异常向上传播。
建议修复
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError(attr) from None参考资料
- Python 数据模型 —
__getattr__:"当默认属性访问因引发AttributeError而失败时被调用" - 内置函数
getattr:"如果指定的属性不存在,且提供了 default 值,则返回它,否则触发AttributeError"
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels