如何确定 AttributeError 指的是哪个属性?

How to determine which attribute an AttributeError refers to?

当我请求一个不存在的 python 对象的属性时,我得到一个 AttributeError,但是我没有在错误对象的字段中找到请求的属性的名称。唯一提到请求属性名称的地方是错误的 args 成员。

在我看来,解析错误消息以获取缺失属性的名称有点烦人。有什么办法可以不用解析报错信息就可以得到缺失属性的名称吗?

演示:

class A:
    def f(self):
        print('in A')


class B:
    pass


class C:
    def f(self):
        print('in C')
        raise AttributeError()


def call_f(o):
    try:
        o.f()
    except AttributeError as e:
        # instead of e.args[0].endswith("'f'") it would be nice to do
        # e.missing_attribute == 'f'
        if e.args and e.args[0].endswith("'f'"):
            print(e.args) # prints ("'B' object has no attribute 'f'",)
        else: raise

if __name__ == '__main__':
    a = A()
    b = B()
    c = C()

    call_f(a)
    call_f(b)
    call_f(c)

目前没有统一的方法来做到这一点。该功能已在 PEP 473 中提出 仍处于草稿状态