DEV Community 👩‍💻👨‍💻

Syed Jafer
Syed Jafer

Posted on

Decorators In Python

Decorators is a way to modify functions dynamically by passing them as arguments to other functions. They are defined by @ followed by func-name.

@func-name

In some cases , we will be needing some steps to be executed before and after some functions. This case can be handled in two ways.

  1. Duplicating code in every functions.
  2. Dynamically modifying functions.

Step 2 is the decorator.

We need to understand that functions are the first class objects. They can be passed by reference, passed by arguments, return from another function, define inside another function.

Inorder to understand better , we shall cook omelete.

Alt Text

Ingridients: Egg (Main Function), Salt,Pepper,Vegetables(Arguments).

Take a tawa, break an egg (functionality) ; add some (arguments) salt, pepper, vegetables (if needed). Cook for 2 mins. Omelete is ready.

Now we have created the omelete . Likewise, we can make some veggies stuff, potato mash and other functionalities. For all these we may include bread to make it a complete dish (Bread Omelete, Sandwich, etc...).

def bread(omelete):
    def inner():
        print("Bread + ",end="")
        omelete()
        print("Bread ",end="")
    return inner

@bread
def omelete():
    print("Omelete + ",end="")

omelete()
Enter fullscreen mode Exit fullscreen mode

Result ,

(base) syed@syed:~/Documents/Decorators$ python dec.py 
Bread + Omelete + Bread 
Enter fullscreen mode Exit fullscreen mode

Here, bread is a common thing that is been included in all dishes mentioned above.

Bread = Decorator
Omelete = Function
Enter fullscreen mode Exit fullscreen mode

Decorators (Breads) are used to remove the duplicate code in the code base.

If you like this, leave a like , comment and make a share .

Top comments (0)

All DEV content is created by the community!

Hey, if you're landing here for the first time, you should know that this website is a global community of folks who blog about their experiences to help folks like you out.

Sign up now if you're curious. It's free!