A Quick Guide to Decorators

Jeffrey Arbelaez
3 min readJul 27, 2023

--

I will be explaining in very basic terms what a decorator is. Imagine that you created a simple function and let’s say you want to add more code to it. Rather than tacking on more and more code this is where decorators come into play. The reason decorators are better in this case is because they are less time consuming and require less coding. We as developers always want to use less key strokes.

Without the decorators we could add more code to the already existing function but this gives us a couple problems. We might not be able to call our original function anymore because now it has new functionalities. You could also keep the original function copy and paste it and make a new function and add the new code but as mentioned before our goal is to type less. Another reason to use decorators is because it works as an on/off switch later. If we hypothetically want to remove the functionality we remove the decorator rather than having to delete the whole code at a later time. Essentially and simpler terms decorators are a concept in Python that allow you to quickly tack on extra functionality to an already existing function. Decorators are easy to write they are simply the @ sign followed by the function name and go right above the function.

In our example below we are building a mini project where we want to time how long each function takes to run. We can go through each function one by one and add a function that times them. That sounds easy when we only have 2. What if we had thousands going though each function individually would take forever.

Rather than go through each function we are going to create a new function that will allow us to reuse it over and over. That function is our timer function. It takes a function as an input. In our wrapper function we define a start time and then invoke the function from timer. Once that is executed we determine how long it took to run by taking our current time and subtracting our start time. Once that is done we just return our wrapper function.

We are still not done! This is where we add the decorators so that we won’t have to go through every function individually. Our decorator is going to be called @ timer and we include it above each function where we want to use it. Python sees the at symbol and knows that the function under it needs to be passed into a function called timer. That function then runs in the timer function and runs through the whole code and executes. If done correctly we should get our results. Which is the time it took and our print ‘Done’ at the bottom.

This a very basic explanation and not one that will allow you to fully grasp the concept. I have included below some helpful videos so that you can further understand.

--

--