Decorator
A decorator in Python is a function that takes another function as its argument, and returns yet another function
- Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.
- Decorators is similar to Closure , Decorator is same Closure which parameter is function and add logic before and after function
1.1. Extending the function with a decorator
- We would like add_together to be able to take a list of 2 element tuples as its argument and return a list of integers which represents the summation of their values.
# Decorator
def decorator1(func):
def wrapper():
print('decorator1')
func()
return wrapper
def decorator2(func):
def wrapper():
print('decorator2')
func()
return wrapper
@decorator1
@decorator2
def hello():
print('hello')
#decorated_hello = decorator1(decorator2(hello))
#decorated_hello()
hello()
"""
decorator1
decorator2
hello
"""
def decorator_list(fnc):
def inner(list_of_tuples):
return [fnc(val[0],val[1]) for val in list_of_tuples]
return inner
@decorator_list
def add_together(x,y):
return x+y
print(add_together([(1, 3), (3, 17), (5, 5), (6, 7)]))
1-2. Decorators that can take arguments themselves
- pass an integer argument to the decorator
- To use arguments in decorators, we simply need to define a decorator itself.
def meta_decorator(power):
def decorator_list(fnc):
def inner(list_of_tuples):
return [fnc(val[0],val[1])**power for val in list_of_tuples]
return inner
return decorator_list
@meta_decorator(2)
def add_together(x,y):
return x+y
print(add_together([(1, 3), (3, 17), (5, 5), (6, 7)]))
> [16, 400, 100, 169]
1-3. Default arguments in Decorators
- callable function set default arg
def meta_decorator(arg):
def decorator_list(fnc):
def inner(list_of_tuples):
return [fnc(val[0],val[1])**power for val in list_of_tuples]
return inner
if callable(arg):
power=2
return decorator_list(arg)
else :
power=arg
return decorator_list
#default option
@meta_decorator
def add_together(x,y):
return x+y
# @meta_decorator(3)
#def add_together(x,y):
# return x+y
print(add_together([(1, 3), (3, 17), (5, 5), (6, 7)]))