CodyKochmann
5/10/2017 - 8:47 PM

get default outputs out of functions with this wrapper instead of crashes.

get default outputs out of functions with this wrapper instead of crashes.

from functools import wraps

class default_output(object):
    """returns the backup plan if the decorated method fails
       by: Cody Kochmann
    """
    def __init__(self, backup_output, logger=print):
        self.backup_output = backup_output
        self.logger = logger

    def __call__(self,func):
        assert callable(func), "default_output needs a callable target to wrap"
        def wrapper(*args, **kwargs):
            print(args,kwargs)
            try:
                return func(*args, **kwargs)
            except Exception as ex:
                # this is where logging would happen
                self.logger(ex)
                # ====================================
                return self.backup_output
        return wrapper