Python Decorators - Part I
Python Decorators - Part l

Python Decorators - Part I

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:

No alt text provided for this image
Example: #1

Let us analyze the above example:

  1. The function `fibonacci()` is simple as its name suggests. It computes the nth fibonacci number in the sequence.
  2. The function `decorator()` takes a function as an argument and returns a closure that computes the running time of the function `func`.
  3. Now, the most important line in the code, `fibonacci = decorator(fibonacci)`. This line means that the function `fibonacci` should be replaced with the function that is returned by a higher-order function `decorator()`.
  4. Now, when you call `fibonacci(5)`, it executes the function `execution_time()`, which was returned by the decorator function because `fibonacci` now holds the reference to the `execution_time()` function.
  5. The function `execution_time()` computes the running time of the original `fibonacci` function because the original `fibonacci` function was passed to the `decorator` function.
  6. Here `fibonacci()` function is also called the decorated function. The `decorator()` function is called the decorator function.
  7. As a result, when you invoke `fibonacci(5)`, then below message it printed in the terminal:

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:

No alt text provided for this image
Example: #2

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:

No alt text provided for this image
Example: #3

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

  1. Decorators are the syntactic sugar to replace a function with another function that takes the same number of arguments and returns the same result.
  2. Decorators are invoked at the import time, i.e. when the module is loaded.

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.

Aman Bhardwaj

Senior Software Engineer at Query | CyberSecurity | I love building Software Stuff

2 年
回复

要查看或添加评论,请登录

Aman Bhardwaj的更多文章

  • Creating Python Packages

    Creating Python Packages

    Introduction Once we have written our code in a Python module, it should be available to use. Now, the next step is to…

  • Python Modules - 1: The Basics

    Python Modules - 1: The Basics

    Welcome to my yet another LinkedIn article related to Python. We will try to understand what are Python modules.

  • A refresher on Compilers

    A refresher on Compilers

    Introduction For sure, compilers are one of the most complicated programs ever written. We have been writing code in…

  • Python Decorators - Part lll

    Python Decorators - Part lll

    This article is in continuation to my previous two articles on decorators. I would encourage you to read both of those…

    1 条评论
  • Python Decorators - Part ll

    Python Decorators - Part ll

    ..

    2 条评论
  • Variable Scoping and Closures in Python

    Variable Scoping and Closures in Python

    Introduction Variable scoping works almost the same way in most programming languages with small differences. Though it…

  • Python's property() class

    Python's property() class

    As we know that in languages like Java, C++, classes are supposed to contain private data attributes as a best coding…

社区洞察

其他会员也浏览了