Sitemap
Harshini M

Harshini M

DECORATORS

A decorator takes in a function, adds some functionality and returns it.

Decorators in Python

Python has an interesting feature called decorators to add functionality to an existing code. This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time.

In order to understand about decorators, we must first know a few basic things in Python.

We must be comfortable with the fact that everything in Python (Yes! Even classes), are objects. Names that we define are simply identifiers bound to these objects. Functions are no exceptions, they are objects too (with attributes). Various different names can be bound to the same function object.

Here is an example.

def first(msg):
print(msg)
first("Hello")second = first
second("Hello")

Output

Hello
Hello

When you run the code, both functions first and second give the same output. Here, the names first and second refer to the same function object. Now things start getting weirder. Functions can be passed as arguments to another function. If you have used functions like map, filter and reduce in Python, then you already know about this. Such functions that take other functions as arguments are also called higher order functions. Here is an example of such a function.

def inc(x):
return x + 1


def dec(x):
return x - 1


def operate(func, x):
result = func(x)
return result

Furthermore, a function can return another function.

def is_called():
def is_returned():
print("Hello")
return is_returned
new = is_called()# Outputs "Hello"
new()

Output

Hello

Here, is_returned() is a nested function which is defined and returned each time we call is_called(). Finally, we must know about Closures in Python.

About Decorators :

Functions and methods are called callable as they can be called.

In fact, any object which implements the special __call__() method is termed callable. So, in the most basic sense, a decorator is a callable that returns a callable.

Get Harshini M’s stories in your inbox

Join Medium for free to get updates from this writer.

Basically, a decorator takes in a function, adds some functionality and returns it.

def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner


def ordinary():
print("I am ordinary")

When you run the following codes in shell.

>>> ordinary()
I am ordinary

>>> # let's decorate this ordinary function
>>> pretty = make_pretty(ordinary)
>>> pretty()
I got decorated
I am ordinary

In the example shown above, make_pretty() is a decorator. In the assignment step:

pretty = make_pretty(ordinary)

The function ordinary() got decorated and the returned function was given the name pretty.

We can see that the decorator function added some new functionality to the original function. This is similar to packing a gift. The decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. But now, it looks pretty (since it got decorated).

Generally, we decorate a function and reassign it as,

ordinary = make_pretty(ordinary).

This is a common construct and for this reason, Python has a syntax o simplify this.

We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be decorated. For example,

@make_pretty
def ordinary():
print("I am ordinary")

is equivalent to

def ordinary():
print("I am ordinary")
ordinary = make_pretty(ordinary)

This is just a syntactic sugar to implement decorators.

How to Add Arguments to Decorators in Python

Decorators can have arguments passed to them. To add arguments to decorators I add *args and **kwargs to the inner functions.

  • *args will take an unlimited number of arguments of any type, such as 10, True, or 'Brandon'.
  • **kwargs will take an unlimited number of keyword arguments, such as count=99, is_authenticated=True, or name='Brandon'.

Here is a decorator with arguments:

from functools import wraps

def my_decorator_func(func):

@wraps(func)
def wrapper_func(*args, **kwargs):
func(*args, **kwargs)
return wrapper_func

@my_decorator_func
def my_func(my_args):
'''Example docstring for function'''

pass

output:

print(my_func.__name__)
print(my_func.__doc__)

# Output

my_func
Example docstring for function