Python Decorator Template

·

1 min read

without arguments

from functools import wraps

def decorate(func):

    @wraps(func)
    def wrapper(*args, **kwargs):
        # some actions before func
        # ...
        _r = func(*args, **kwargs)
        # some actions after func
        # ...
        return _r

    return wrapper

with arguments

from functools import wraps

def decorate(*decorate_args, **decorate_kwargs):

    def real_decorate(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            # some actions before func
            # ...
            _r = func(*args, **kwargs)
            # some actions after func
            # ...
            return _r

        return wrapper

    return real_decorate