Python Decorators

Mayank Porwal
4 min readNov 5, 2020
python decorator
Photo by Kevin Ku on Unsplash

Decorators in Python is an advanced topic. Before we dive into Python Decorator we need to understand the concepts of python functions. In this article we will go through the python decorator in details including's some different examples.

In this article we are going to explore the following things:

  1. What are functions in Python??

2. What is python decorators??

3. Basic Syntax of Decorator

4. Create a Simple Decorator

5. Create a Multiple Decorator

6. Class based Decorator

What are functions in Python??

In python functions are the first class objects that can be referenced to, passed to another a variable and returned from other functions as well.

In Python, everything is an object including all datatypes like int, float, dict, list etc. are objects in python. Functions in python are also objects.

Let’s take a look at an example to understand how it works.

say_hi is simple function which prints Hi .

def say_hi:
print("Hi")
# say_hi() Output: Hi

In below code we have assigned say_hi to say_hi2. You can see that say_hi and say_hi2 will print the same output Hi means both have same output. We can also check with == operator.

print(say_hi == say_hi2)# Output: True

On the other side we can also check the memory address of the function. Both are point to same address space.

print(say_hi)# Output: <function say_hi at 0x00000152AE323D30>print(say_hi2)# Output: <function say_hi at 0x00000152AE323D30>

Inner Functions

Functions can also be defined in another function and inner function can also be passed as argument to another function.

def say_hi():
print("Hi")
def say_hello():
print("Hello")
def greet(func):
return func
greet(say_hi)()greet(say_hello)()

Output:

Hi
Hello

Here we are passing function references to greet function as an argument that returns the reference again.

This is How Inner function works:

def greet():def say_hi():
print("Hi")
def say_hello():
print("Hello")
say_hi()
say_hello()
greet()

Output:

Hi
Hello

What is python decorators??

You have seen that functions are just like another object in Python. Now we can move to decorators.

Python has an awesome feature to add functionality to existing code without permanently modifying it. The function behavior only changes when its decorated.

Basic Syntax of Decorator

A decorators wraps a function and modify its behavior. let’s take a look at a simple example of decorator and understand how we can work with decorators:

def simple_decorator(func):
print("Before function call....")
func()
print("After function call....")
return func
def say_hi():
print("Hi")
say_Hi = simple_decorator(say_hi)

Output:

Before function call....
Hi
After function call....

Create a Simple Decorator

Let’s make things little easier to understand Python decorators. Look at an example below:

def simple_decorator(func):
print("Before function call....")
func()
print("After function call....")
return func
@simple_decorator
def say_hi():
print("Hi")

Output:

Before function call....
Hi
After function call....

The output will be similar to the above program. The only difference we have used syntax with @ symbol.

Multiple Decorators

In the above example we have only used one decorator to the function. However, we can also use multiple decorators to decorate functions at the same time.

Let’s see with this example.

In the above example you can see that we simply created another decorator which calls the decorated function twice. We also defined two functions say_hi and say_hello that are decorated by two decorators. However both functions are decorated in different order which will generate different outputs.

  • We notice that say_hello gets called twice and decorator logging_time is applied once. Meanwhile the say_hi gets called twice and also decorator logging_time is applied twice.
  • When we have multiple decorators the hierarchy it follows from bottom to top. This is why say_hello function gets decorated by logging_time once — because the logging_time decorator is applied last. The repeater decorator applies to the function say_hi which is already been decorated by logging_time decorator, and thus the time for say_hi function logged twice.

Class based decorators

In python decorators can be either functions or classes. We can also define a decorator as a class, to implement we need to use __call__ method of classes.

We can create class decorator by @ symbol followed by class name, right above the function definition. In class definition, we define two method: the init constructor and the magic call() method.

When we decorate a function with class decorator using argument, the argument is automatically passed to its init constructor. The magic method takes function as an argument. Inside this we define a repeat_wrapper method.

In this example we create a class decorator which takes argument.

In the above example we can see that two method say_hi and say_hello which is decorated by class decorator Repeater with arguments 2 and 4 respectively and after calling those method, this gives output accordingly. When we pass an argument to class decorator, that argument not the function is passed as the argument to the init constructor. The integer value is saved as an argument, n in the object. The repeat_wrapper function contains the loop that calls the decorated function n times.

Thanks for reading…..

Feel free to leave a comment or share this post. Follow me for future posts….

--

--