Skip to content
Advertisement

How to catch an AttributeError in Background through Decorator?

this is raising an AttributeError in the moment:

JavaScript

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

JavaScript

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 :

JavaScript

outputs

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement