• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Step-by-step] Python Decorators Explained with Examples for Beginners

Aniruddha Chaudhari/25461/4
CodePython

Python decorators are considered as one of the very advanced and very useful concepts.

In this tutorial, I will explain Python decorators with examples. Going through this tutorial, you will learn to implement Python decorators and how it can be very useful in your project.

Table of Contents

  • What is Python Decorators?
  • Python Decorators Explained
    • Python Decorator Basic Example
    • Python Decorators Example with Two Arguments
  • When to Use Python Decorators?

What is Python Decorators?

This is one of the very popular Python interview questions asked in the IT job interviews.

Python decorators is a technique for changing the behavior of an existing function without changing actual code inside the function.

Even though we are changing the behavior of the function, there should not have any change in the function definition and function call.

It means…

  • The code inside the original function should not be changed.
  • There should not have any change in the function call.

Python has a special mechanism called Python decorators to change the behavior of the existing function.

It might be a bit confusing to you. Let’s go with an example.

Python Decorators Explained

How does Python Decorator work?

Let’s start with a simple Python function code.

def myFunc():
  print("Hello, World!")

myFunc()

Output:

Hello, World!

This is the basic Python program to implement a Python function. If you are new to Python programming, check basic Python code syntax.

Now consider a function that you want to wrap inside another function (called decorator).

It is similar to the technique of wrapping gifts inside flashy decorative papers.

Let’s see how it can be implemented in Python.

We know, that everything in Python is an object including the Python function. It means, we can pass the function object as an argument to another function. By default, the function name works as a function object.

We can write one Python function inside another function.

def myWrapper(func):
  def myInnerFunc():
    print("Inside wrapper.")
    func()
  return myInnerFunc
 
def myFunc():
  print("Hello, World!")

c=myWrapper(myFunc)
c()

Output:

Inside wrapper.
Hello, World!

Here we are passing the function (myFunc) as a parameter to the wrapper function (myWapper).

This is how it works.

  • The actual function is passed as a parameter to the wrapper function.
  • myWrapper has an inner function which calls the actual function (myFunc).
  • Inside Inner function, you can write any additional operation to perform along with calling the original function (myFunc).
  • myWrapper returns the inner function object.

Note: When you write function name without brackets, it acts as a function object and it does not call function. The function gets called only when there is a function name (object) followed by brackets “()”.

If you compare the above two programs, you have changed the behavior of the original function. You can see the difference in the output.

We have fulfilled the first criteria of not changing code inside the function.

But the function call has changed

from

myFunc()

to

c=myWrapper(myFunc)
c()

This does not fulfill our second criteria.

Here is the use of Python decorators.

Python Decorator Basic Example

def myWrapper(func):
  def myInnerFunc():
    print("Inside wrapper.")
    func()
  return myInnerFunc
 
@myWrapper
def myFunc():
  print("Hello, World!")

myFunc()

Output:

Inside wrapper.
Hello, World!

Python decorator name (@myWrapper) is specified above the actual function definition. (2)

How does the Python decorator program execute?

Python Decorators Explained

Below are the steps of execution.

  • The original function is called (1).
  • There is a function wrapper name specified above the function definition (2). This indicates, that there is a function decorator assigned to the function.
  • The decorator function gets called. The program controller passes the function object as a parameter to the decorator function (3).
  • The function inside the decorator function gets executed (4).
  • The inner function calls the actual function (5).
  • The original function starts execution (6).

This is a simple Python decorator example. You can also pass the arguments to the Python decorators.

Many get confused decorators with the monkey patching techniques in Python. Two are the different things.

Python Decorators Example with Two Arguments

Original Function to add two numbers.

def addTwoNumbers(a, b):
    c=a+b
    return c

c=addTwoNumber(4, 5)
 
print("Addition of two numbers=", c)

Output:

Addition of two numbers=9

Now our aim is to modify the behavior of addTwoNumbers() without changing function definition and function call.

What function behavior do we want to change?

We want addTwoNumbers function should calculate the sum of the square of two numbers instead of the sum of two numbers.

Here is a simple decorator to change the behavior of the existing function.

def decorateFun(func): 
    def sumOfSquare(x, y): 
        return func(x**2, y**2) 
    return sumOfSquare 

@decorateFun
def addTwoNumbers(a, b): 
    c = a+b 
    return c 

c = addTwoNumbers(4,5) 
print("Addition of two numbers=", c)

Output:

Addition of two numbers=41

The below simple program is equivalent to the above decorator example. Here we are changing the function call.

def decorateFun(func): 
    def sumOfSquare(x, y): 
        return func(x**2, y**2) 
    return sumOfSquare 

def addTwoNumbers(a, b): 
    c = a+b 
    return c 

obj=decorateFun(addTwoNumbers) 
c=obj(4,5) 
print("Addition of square of two numbers=", c)

Output:

Addition of square of two numbers=41

Note: The number of arguments to the function inside the decorators should be the same as the number of arguments to the actual function.

When to Use Python Decorators?

Suppose you are working on a project. You are asked to make the changes in a certain complex function.

If you are making changes in already tested and robust functions, you can not deny the possibility of breaking functionality.

A better way is to use Python decorators.

  • You don’t need to make changes in the already tested function.
  • You don’t need to make any changes to the function call. This will be very useful if there are multiple function calls in your project source code.

You can also pass the arguments to the decorators. You can modify these arguments inside the decorators before passing them to the original function.

This is all about Python decorators explained with examples. If you have any questions, ask in the comment section below.

After decorators, learn lambda function which is another advance topic in Python programming.

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Alas
    April 7, 2020 at 8:47 pm

    Mr. Chaudhari
    c=obj(4,5) give a result 881 ((4^2)^2+(5^2)^2)

    • Reply
      Aniruddha Chaudhari
      April 8, 2020 at 7:56 am

      Alas, It gives a result 41 (4^2+5^2). You are calculating power twice which is not correct.

  • Reply
    Python fan
    February 16, 2021 at 5:51 pm

    Great and more than clear explanation. Many thanks!

    • Reply
      Aniruddha Chaudhari
      February 18, 2021 at 11:03 am

      I’m glad as a Python fan finds it helpful. Next time I would love to see your name. 😀 Good day!

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard