UrbanPro
true

Learn Python Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

What is a Decorator in Python?

Amitava Majumder
25 Jun 0 0

🎀 What is a Decorator in Python?

decorator in Python is a powerful tool that allows you to modify or enhance the behavior of functions or methods without changing their actual code. Decorators use the @decorator_name syntax and are widely used in logging, access control, memoization, and more.

They are ideal when:

  • 🔄 You want to reuse common logic across multiple functions.
  • 🔐 You need to add extra functionality like authentication, logging, or timing.

🛠️ Real-Time Use Cases

  • 📋 Logging: Automatically log function calls without modifying the original function.
  • ⏱️ Timing: Measure how long a function takes to run.
  • ✅ Authentication: Add security checks before allowing a function to execute.
  • 📦 Memoization: Cache results of expensive function calls (e.g., in data science apps).
  • 📚 Web Frameworks: Flask/Django use decorators for routing URLs to views.

💡 Example: Basic Decorator

def my_decorator(func):
    def wrapper():
        print("Before the function runs")
        func()
        print("After the function runs")
    return wrapper

@my_decorator def greet(): print("Hello, World!")

greet()

import time

def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"⏱️ Execution time: {end - start:.4f} seconds")
        return result
    return wrapper

@timing_decorator
def long_running_task():
    total = 0
    for i in range(1, 10_000_000):
        total += i
    print("✅ Task Completed.")
    return total

# Call the function
long_running_task()
 
 
✅ Task Completed.
⏱️ Execution time: 1.0263 seconds
Out[23]:
49999995000000
 
In [28]:
import datetime

def log_function_call(func):
    def wrapper(*args, **kwargs):
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_entry = (
            f"[{timestamp}] 📝 Called function: '{func.__name__}'\n"
            f"➡️ Arguments: {args}, Keyword Arguments: {kwargs}\n"
        )
        result = func(*args, **kwargs)
        log_entry += f"✅ Result: {result}\n\n"
        
        print(log_entry)

        # Fix encoding issue by using utf-8
        with open("log.txt", "a", encoding="utf-8") as log_file:
            log_file.write(log_entry)
        
        return result
    return wrapper
 
 

💡 How to Use:
Example 1: Login

 
In [29]:
@log_function_call
def login(username):
    return f"User '{username}' logged in."

login("admin")
 
 
[2025-06-16 13:35:17] 📝 Called function: 'login'
➡️ Arguments: ('admin',), Keyword Arguments: {}
✅ Result: User 'admin' logged in.


Out[29]:
"User 'admin' logged in."
 
 

Example 2: API Call

 
In [30]:
@log_function_call
def get_data(endpoint, id=0):
    return {"endpoint": endpoint, "id": id}

get_data("user", id=101)
 
 
[2025-06-16 13:35:29] 📝 Called function: 'get_data'
➡️ Arguments: ('user',), Keyword Arguments: {'id': 101}
✅ Result: {'endpoint': 'user', 'id': 101}


Out[30]:
{'endpoint': 'user', 'id': 101}
 
 
  1. Monitoring Scheduled Job
 
In [31]:
@log_function_call
def daily_backup():
    return "Backup completed successfully."

daily_backup()
 
 
[2025-06-16 13:35:57] 📝 Called function: 'daily_backup'
➡️ Arguments: (), Keyword Arguments: {}
✅ Result: Backup completed successfully.


Out[31]:
'Backup completed successfully.'
 

📊 Summary: Decorator Benefits

Feature Decorator
♻️ Code Reuse High — reuse logic across functions
✨ Enhancing Functions Without changing original function code
📈 Common Use Cases Logging, timing, auth, web routes
📌 Syntax Uses @decorator above function
0 Dislike
Follow 1

Please Enter a comment

Submit

Other Lessons for You

Small ML Project on Simple Linear Regression
Here is a small Project on Simple Linear Regression

Build an interactive Dictionary using Python 3.x
I have downloaded a 5MB data base consisting of words and their meanings in a json file . I want to write a python progrsm which will ask the user to enter a word and then the program will search through...
B

Biswanath Banerjee

0 0
0

Multiple Decorators
#Multiple decorators can be chained in Python.#A function can be decorated multiple times with different (or same) decorators.#We simply place the decorators above the desired function. def star(func):...

Python : functional programming characteristics
Functions are first class (objects). That is, everything you can do with "data" can be done with functions themselves (such as passing a function to another function). Recursion is used as a primary...

Things to learn in Python before choosing any Technological Vertical
Day 1: Python Basics Objective: Understand the fundamentals of Python programming language. Variables and Data Types (Integers, Strings, Floats, Booleans) Basic Input and Output (using input()...
X

Looking for Python Training Classes?

The best tutors for Python Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Python Training with the Best Tutors

The best Tutors for Python Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more