Decorators
- takes A function that takes 1 function as input and returns another function
- my_decorator is a function that takes another function func as its parameter.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called: Inside my_decorator, a new function wrapper is defined.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Calling the decorated function
say_hello()
def document_it(func):
def new_function(*args, **kwargs):
print('Running function: ', func___name__)
print('Positional arguments: ', args)
print('Keyword arguments: ', kargs)
result = func(*args, *kargs)
print('Result: ', result)
return result
return new_function
- whatever func you pass to document_it(), you get a new function that includes the xtra statements that document_it() adds.
def add_ints(a,b):
return a+b
add_ints(3,5)
# Output
8
cooler_add_ints = document_it(add_ints) # manual decorator assignment
cooler_add_ints(3,5)
# Output
Running function: add_ints
Positional arguments: (3,5)
Keyword arguments: {}
Result: 8
8
- as an alternative to the manual decorator assignment, you can add @decorator_name before the function
@document_it
def add_ints(a,b):
return a+b
add_ints(3,5)
# Output
Start Function add_ints
Positional arguments: (3,5)
Keyword arguments: {}
Result: 8
8
- you can have more than one decorator for a function page160