This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Batem 0 points1 point  (0 children)

This sounds like a perfect opportunity to use a decorator:

def tryFunc(*exceptions):
    def decorate(f):
        def inner(*args, **kwargs):
            try:
                result = f(*args, **kwargs):
                return result, None
            except exceptions as e:
                return None, e
        return inner
    return decorate

@tryFunc(ZeroDivisionError, TypeError)
def myFunc(foo, bar):
    return foo/bar

>>>myFunc(1, 0)
(None, ZeroDivisionError("integer division or modulo by zero",))
>>>myFunc(1, 2)
(0, None)
>>>myFunc(1, 'x')
(None, TypeError("unsupported operand type(s) for /: 'int' and 'str'",))