Python Decorators - Part I
Aman Bhardwaj
Senior Software Engineer at Query | CyberSecurity | I love building Software Stuff
Introduction
Decorators are one of the widely used concepts in Python. I have not encountered a Python codebase, yet, where decorators are not used. They fascinated me because, for the first time, I saw in Python how you can alter the behavior of a function without making changes to the function itself. In this article, I will make understanding decorators a lot easier. The entire decorator topic will be covered in three parts. This article covers the first part which familiarises you with decorators and removes the fear in you about decorators. Now, let's begin.
Please note that a good understanding of closures is really important before understanding decorators. I would recommend reading my article on closures or you can simply learn it from anywhere on the internet. For convenience, I am providing the link to my article on closures. Now let's begin.
What is a decorator?
Decorators are a way of replacing a function with a new function accepting the same number of arguments and returning the same result. In Python, everything is treated as an object including functions. Because it is common to replace an object with another object, the same is valid for functions too. But why do we need decorators to replace a function with another function? Decorators are nothing but syntactic sugar. Let me walk you through an example:
Let us analyze the above example:
The time taken is 3.5762786865234375e-06
The reuslt is: 3
There was no use of decorator in the above example, but the same can be accomplished by writing `@decorator` above the `fibonacci()` function's definition and omitting the line `fibonacci = decorator(fibonacci)` as shown below:
领英推荐
When are the decorators executed?
It is important to understand that the decorators are executed at the import time of the module. Import time is the time when the module is loaded by Python. It is often misunderstood that the decorators are executed when the decorated function is invoked, but that's not true. To showcase this, let's see a very simple example below:
Please note that we have not called the function `add_nums()` anywhere in our code, but still you will see the output as:
Decorator is invoked!
Summary
With that, I hope that this introduction to the decorators was simple and easy to understand. If you liked it, please follow me for more such articles on Python.
Senior Software Engineer at Query | CyberSecurity | I love building Software Stuff
2 年Link to my article on Closures: https://www.dhirubhai.net/pulse/variable-scoping-closures-python-aman-bhardwaj/?trackingId=LOBcgVR2T3O9Wb2MSN6fDw%3D%3D