Hodor Hodor - 1 year ago 60
Python Question

Use decorators to wrap all functions with "if func returned false, return false"

I'm writing a very basic Python script based on a

function that sequentially calls other functions.

What I would like to do is to wrap all of the functions that are called from
with something like:

result = func(*some_args):
if (result != True):
return result

For example, for this code:

def func1(arg1 , arg2):
if (some_cond):
return False #Or some err_val
return True

def func2(arg1):
if (some_cond):
return False
return True

def main():
func1(val1 , val2)
return True

if __name__ == "__main__":
import sys
result = main()
if (result == err_val1):
# Do something. Maybe print. Maybe call some function.

I want that if one of the functions fails
would break and return its error. Can I do this using decorators?

Answer Source

I guess, what you really want is a universal exception catcher, that would catch and return the exception of any wrapped function. You can easily do it this way.

def return_exception(func):
    def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        except Exception as e:
            return e
    return wrapper


In [3]: @return_exception
   ...: def div(a, b):
   ...:     return a / b

In [4]: div(1, 0)
Out[4]: ZeroDivisionError('division by zero')

So then you can process the return exception object the way you want, though it's pretty hard to say why you need that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download