5/13/2020

Python - Decorators With Arguments

** Decorators With Arguments


==========================================

def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print('Executed After', original_function.__name__, '\n')
return result
return wrapper_function


@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))


display_info('John', 25)
display_info('Travis', 30)

---------------------------------

Executed Before display_info
display_info ran with arguments (John, 25)
Executed After display_info

Executed Before display_info
display_info ran with arguments (Travis, 30)
Executed After display_info

---------------------------------

==========================================

def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function

@prefix_decorator('TESTING:')
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))


display_info('John', 25)
display_info('Travis', 30)

---------------------------------

TESTING: Executed Before display_info
display_info ran with arguments (John, 25)
TESTING: Executed After display_info

TESTING: Executed Before display_info
display_info ran with arguments (Travis, 30)
TESTING: Executed After display_info

---------------------------------

==========================================

def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function

@prefix_decorator('LOG:')
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))


display_info('John', 25)
display_info('Travis', 30)

---------------------------------

LOG: Executed Before display_info
display_info ran with arguments (John, 25)
LOG: Executed After display_info

LOG: Executed Before display_info
display_info ran with arguments (Travis, 30)
LOG: Executed After display_info

---------------------------------