Rizhiy
Rizhiy

Reputation: 854

Get class and attribute names from AttributeError

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

Answers (3)

Niko Fohr
Niko Fohr

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()
  • First cast the error into text with str(e)
  • Then, using regular expression pattern read the object type and the name of the attribute you're trying to access. The groups() method will return all the captured groups from the regex which are marked with parenthesis.

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

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

ForceBru
ForceBru

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

Related Questions