Pages

Wednesday, 19 December 2018

A failsafe decorator for a python class

Often a Python class may have lots of bound methods that may fail, but it is not really a problem. Here I present a tidy way to deal with catching the errors with a decorator.
Errors in Python are caught with the try-except pair.
Repeating this combination for every call can make your code bad and the response would need to be changed in each entry (the classic reason why copy-pasting code is a bad idea). Therefore making a decorator to catch them is a nice approach.
A decorator is a method that wraps another one (the output of the wrapped gets fed to the wrapper) and is implemented with a line above the wrapped function with the name of the wrapper preceded by an at key. Technically the wrapper is implemented as a method generator that returns a function, hence arguments can be given to the wrapped function. A bound method decorator is special case. Here is the decorator I use to decorate the bound methods (added with the methods of the class, when called as a decorator simply @failsafe, no self.

No comments:

Post a Comment