Skip to main content

Decorators. What? Why? When?


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 # Call the function hello() # Now calling the decorator my_decorator(hello)() success_msg("Great job!")


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? 


*Enters Decorator*

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. :)

If anything is wrong please inform m.... See you soon with more post.
Have a good day.

Comments

Popular posts from this blog

Generators in Python

One of the most commonly asked question in Python interviews is "Have you worked with generators? How and what was the need to use it?" This post will try to explore what are they how and why they are used? Basically, Generator in simple terms can be thought as the function which returns series of results instead of one single result. Syntactic difference between function and generator is, Generator uses "yield" keyword instead of "return" keyword. Generators give us an iterator(Something which we can loop on for ex. list or dictionary) so they can be used with looping constructs such as 'for' and 'while' loops. Example: # Define a generator. def generator(number): while True: number += 1 yield number # Use the generator. x = generator(5) # Now calling the decorator print("Calling generator:") x.next() print("Calling generator:")

Immutable vs Mutable Data structures.

Majorly used Data Structures in python are as follows: List Set Tuple Dictionary String Numbers(int, float, decimal) One of the major things in python discussed is whether the data structure is mutable or immutable. What do this terms mean? In simple terms, Immutable means value cannot be changed after it is assigned to a variable. Whereas, In  mutable data type value can be changed after assignment. Hmm, What ??? This is still not clear these are merely dictionary definitions I am blabbering. Amazon.in Widgets