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
1 day ago 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

Code: Gantt Chart: Horizontal bar using matplotlib for tasks with Start Time and End Time
import pandas as pd from datetime import datetimeimport matplotlib.dates as datesimport matplotlib.pyplot as plt def gantt_chart(df_phase): # Now convert them to matplotlib's internal format... ...
R

Rishi B.

0 0
0

Python Script for random Password generation
from random import randintdef passwordgen(request): str_not_include = "1 L I i l o O 0" str_small ="abcdefghjkmnpqrstuvwxyz" str_caps = str_small.upper() str_num = "23456789" str_special...

A python program using the datetime module
Task : To write a program in Python to find out, in any given year, Friday the 13th dates i.e 13th day of a month which was a Friday. ...

Black in Python
When you are upturn in your career from beginner to experienced in programming world, your team will start looking at ‘how you are writing?’ Here the responsibility piling up. Okay,...

A program to calculate Correlation Coefficient
Task: Calculating the Correlation-coefficient using Python We know that the correlation coefficient is calculated using the formula nΣxy- ΣxΣy / (√(nΣx^2-(Σx)^2)...
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