Skip to content

DashScopeAPIResponse.__getattr__ raises KeyError instead of AttributeError #114

@marklysze

Description

@marklysze

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 missing

Impact

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 False

getattr(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 None

References


中文说明

问题描述

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,而非返回 False

getattr(obj, name, default)hasattr(obj, name) 都依赖 AttributeError 来触发默认值/回退逻辑。KeyError 会作为未处理的异常向上传播。

建议修复

def __getattr__(self, attr):
    try:
        return self[attr]
    except KeyError:
        raise AttributeError(attr) from None

参考资料

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions