A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure
def uppercase_decorator(function):
def wrapper(*args,**kwargs):
= function()
fun_output = fun_output.upper()
make_uppercase return make_uppercase
return wrapper
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
## 'HELLO THERE'
*args and **kwargs collect all positional and keyword arguments and stores them in the args and kwargs variables.
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
def a_wrapper_accepting_arbitrary_arguments(*args,**kwargs):
print('The positional arguments are', args)
print('The keyword arguments are', kwargs)
return function_to_decorate(*args,**kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print(a, b, c)
1,"a",3) function_with_arguments(
## The positional arguments are (1, 'a', 3)
## The keyword arguments are {}
## 1 a 3
@a_decorator_passing_arbitrary_arguments
@uppercase_decorator
def function_with_keyword_arguments():
return "This has shown keyword arguments"
="Derrick", last_name="Mwiti") function_with_keyword_arguments(first_name
## The positional arguments are ()
## The keyword arguments are {'first_name': 'Derrick', 'last_name': 'Mwiti'}
## 'THIS HAS SHOWN KEYWORD ARGUMENTS'
function_with_keyword_arguments()
## The positional arguments are ()
## The keyword arguments are {}
## 'THIS HAS SHOWN KEYWORD ARGUMENTS'