Skip to content
Advertisement

How to catch an AttributeError in Background through Decorator?

this is raising an AttributeError in the moment:

from functions import *

class Class:
    def __init__(self):
        self.name = 'Name'

    @exception_handler
    def do_stuff(self):
        print('Stuff')

if __name__ == '__main__':
    test = Class()
    test.dooo_stuff()

AttributeError: ‘Class’ object has no attribute ‘dooo_stuff’

I want to catch this Attribute Error somehow with an Decorator in Background. So that i can inform the user that the class method name has changed.

So

try:  
    test = Class()
    test.dooo_stuff()
except AttributeError:
    print('info')

will not work because that is not in Background. I want to change the Error Message above to notify the user. Is there any way to do that? Thanks

Advertisement

Answer

The Python Data Model is very powerfull. You can customize attribute access with the dunder method __getattr__ :

Called when the default attribute access fails with an AttributeError […] This method should either return the (computed) attribute value or raise an AttributeError exception.

Although the usual usage is to provide dynamic values (that is how mock or defaultdict are implemented for example), it is possible to execute any code we want, for example calling a callback :

def handler(attribute_error_name):
    print(f"{attribute_error_name!r} does not exist")


class MyAPI:
    def do_stuff(self):
        return "done"

    def __getattr__(self, item):
        handler(item)
        return lambda: None  # if the return value is not callable, we get TypeError: 'NoneType' object is not callable

api = MyAPI()
print(api.do_stuff())
print(api.do_something_else())

outputs

done
'do_something_else' does not exist
None
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement