Anton Daneyko Anton Daneyko - 1 year ago 82
Python Question

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

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?


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

class B:

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

def call_f(o):
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()


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download