Skip to content
loading...

re: Python Decorator Tutorial with Example VIEW POST

FULL DISCUSSION
 

There's also the pattern with functools.partial that allows you to call decorators with optional arguments without the parenthesis if you want to use the default values.

from functools import partial, wraps

def print_result(func=None, *, prefix=''):
    if func is None:
        return partial(print_result, prefix=prefix)

    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print(f'{prefix}{result}')
        return result
    return wrapper

Now you can apply the decorator without the parenthesis if you want to use the default value.

@print_result
def add(a, b):
    return a + b

add(2, 3)  # outputs '5'

@print_result()
def add(a, b):
    return a + b

add(2, 3)  # outputs '5'

@print_result(prefix='The return value is ')
def add(a, b):
    return a + b

add(2, 3)  # outputs 'The return value is 5'

There's no way of getting it wrong when you apply the decorator. IMO it's the simplest and most readable pattern. I use it all the time.

code of conduct - report abuse