The biggest reason for storing try / except / finally blocks in the code itself is that error recovery is usually an integral part of the function.
For example, if we have our int() function:
def MyInt(text): return int(text)
What if text cannot be converted? Return 0 ? Return None ?
If you have a lot of simple cases, I see that a simple decorator is useful, but I think that the recipe you linked tries to do too much: it allows you to activate another function for every possible exception - in cases like those (several different exceptions , several different codes), I would recommend a dedicated wrapper function.
Here is my approach to a simple decorator:
class ConvertExceptions(object): func = None def __init__(self, exceptions, replacement=None): self.exceptions = exceptions self.replacement = replacement def __call__(self, *args, **kwargs): if self.func is None: self.func = args[0] return self try: return self.func(*args, **kwargs) except self.exceptions: return self.replacement
and sample use:
@ConvertExceptions(ValueError, 0) def my_int(value): return int(value) print my_int('34')
Ethan Furman Mar 10 2018-12-12T00: 00Z
source share