Search code examples
pythonexceptionerror-handlingstandard-libraryanti-patterns

How to determine which attribute an AttributeError refers to?


When I ask for an attribute of a python object that does not exist, I get an AttributeError, however I have not found the name of the requested attribute among the fields of the error object. The only place which mentions the name of the requested attribute is args member of the error.

It seems to me a bit of an annoyance to parse the error message in order to get the name of the missing attribute. Is there any way to get the name of the missing attribute without parsing the error message?

Demo:

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)

Solution

  • There is no uniform way to do that currently. The feature has been suggested in PEP 473 which is still in draft form