如何确定AttributeError引用的属性?

时间:2016-11-21 14:48:20

标签: python exception error-handling standard-library anti-patterns

当我要求一个不存在的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)

1 个答案:

答案 0 :(得分:0)

目前没有统一的方法可以做到这一点。 PEP 473中建议使用此功能 仍处于草案状态