Py Decorator
Py Decorator
Background
Following are important facts about functions in Python that are useful to understand decorator
functions.
We know Decorators are a very powerful and useful tool in Python since it allows programmers to
modify the behavior of function or class. In this article, we will learn about the Decorators with
Parameters with help of multiple examples.
Python functions are First Class citizens which means that functions can be treated similarly to
objects.
# Nested function
def addWelcome():
return "Welcome to "
print messageWithWelcome(site("Developer"))
Function Decorator
A decorator is a function that takes a function as its only parameter and returns a function. This is
helpful to “wrap” functionality with the same code over and over again. For example, above code
can be re-written as following. We use @func_name to specify a decorator to be applied on another
function.
Example 2
# Adds a welcome message to the string
# returned by fun(). Takes fun() as
# parameter and returns welcome().
def decorate_message(fun):
# Nested function
def addWelcome(site_name):
return "Welcome to " + fun(site_name)
@decorate_message
def site(site_name):
return site_name;
# Driver code
# This call is equivalent to call to
# decorate_message() with function
# site("Developer") as parameter
print site("Developer")
Decorators can also be useful to attach data (or add attribute) to functions.
Example 3
# A Python example to demonstrate that
# decorators can be useful attach data
@attach_data
def add (x, y):
return x + y
# Driver code
print(add.data)
@log_decorator
def add(a, b):
return a + b
result = add(2, 3)
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(a, b):
return a + b
def decorator_fun(func):
print("Inside decorator")
def func_to():
print("Inside actual function")
func(*args, **kwargs)
return wrapper
return Inner
This example also tells us that Outer function parameters can be accessed by the enclosed inner
function. Scope of variable is availble inside the inner function.
Example
# Python code to illustrate
# Decorators with parameters in Python (Multi-level Decorators)