Codementor Events

Decorators in python. What? Why? When?

Published Nov 02, 2018

In this post, we will look at decorators.

We will try to address following questions:

What are they? Why they are needed? and when are they useful?
Ok, let's look at them one by one.

First: What are they?

Simply put, From what I understand:
Decorators are functions that take another function as input and modifies/extends its functionality.

Wait...what? A function that takes another as input?
Yes, In Python everything is an object (Classes too.). So we can pass a function as arguments.

What do you call a function which takes another function as arguments? : Higher order function.

Till now all text, no code. Let's look at an example. Let's write a simple decorator:

# Create a simple function.
def hello():
    print("Hello user!.")

# Now we Define a decorator.
def my_decorator(some_function):

    def wrapper():
        print("I will check if the user is logged in or not before saying hello!")
        some_function()
        print("I want to say goodbye after it.")

    return wrapper

**What we did here? **

We defined a simple function and decorated it with another function.

You might wonder, why introduce a new function? Why not alter the actual function itself?

To answer this, let's look at a problem.

Suppose you are working on a website.

Now there is a requirement not to proceed further if the user is not logged in.

Now, One way to do this is to check each function that needs this "is the user logged in?" check and modify those functions one by one.

Problem is: This can be time-consuming and repetitive code blocks inside each function.

**Solution? **

** Enter Decorators **

Instead, if we write a decorator and plug it on top of each function that needs the check it will be much cleaner and DRY (Don't Repeat Yourself) code!!

This will lead us to answer our two questions when and why they are needed?

Most of the time decorators are used in places where we want to alter/extend many functions in the same way.

One of the examples where I have used in my work experience is the user logged in check.

Do you know any other use cases? Please let us know in comments thanks. 😃

Discover and read more posts from Kishan S Mehta
get started
post commentsBe the first to share your opinion
Show more replies