Apologies this is a very broad question.
The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protect
First, we need to understand why we need Decorator.
Need for decorator: We want to use the function of already built-in Library from Python which can perform our desired task.
Problems: But problem is that we don't want exact function output. We want customized output. The trick is that we can't change the original code of the function. here decorator comes to our help.
Solutions: Decorator takes our required function as input, wraps it in a wrapper function and does 3 things:
Overall code:
def my_decorator(desired_function):
def my_wrapper():
print "do something before" #do something before, if you want to
desired_function()
print "do something after" #do something after, if you want to
return my_wrapper
desired_func = my_decorator(desired_func()) #create decorator
desired_func() #calling desired_func()