Reputation: 854
How do I get the class and missing attribute from AttributeError, e.g.
when AttributeError says: 'NoneType' object has not attribute a
, I would like to get "NoneType"
and "a"
.
Upvotes: 1
Views: 145
Reputation: 33830
import re
try:
# access attribute
except AttributeError as e:
obj_type, attr_name = re.match(r"\'([a-zA-Z0-9\_]+)\' object has no attribute \'([a-zA-Z0-9\_]+)\'", str(e)).groups()
str(e)
groups()
method will return all the captured groups from the regex which are marked with parenthesis.Upvotes: 1
Reputation: 24691
For getting the type information out of an AttributeError, you could probably use regex, since you know the format of the error message:
import re
try:
None.attr
except AttributeError as e:
matches = re.match(r"'([^']*)' object has no attribute '([^']*)'", str(e))
obj_type = matches.group(1)
attr_name = matches.group(2)
print(f"Object type: {obj_type}, attribute name: {attr_name}")
# Object type: NoneType, attribute name: attr
Upvotes: 1
Reputation: 44848
Looks like the only thing you can retrieve from an AttributeError
is the string with the error message:
try:
str.s
except AttributeError as err:
error_message, = err.args
print("Error message:", error_message)
raise
Upvotes: 2