Create a Customized Decorator for Task

Sometimes you might want to change the behavior of a task. Here is the sample code to create a customized task decorator:

def custom_task(func=None, *task_init_args, **task_init_kwargs):
    if func is None:
        return partial(custom_task, *task_init_args, **task_init_kwargs)
    
    @wraps(func)
    def safe_func(*args, **kwargs):
        try:
            res = func(*args, **kwargs)
            print(f"The returned value of {func.__name__} is {res}.")
            return res
        except Exception as e:
            print(e)
    safe_func.__name__= func.__name__
    return task(safe_func, *task_init_args, **task_init_kwargs)
1 Like