UrbanPro
true
default_background

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/06/2025 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

Why Do People Choose Python?
Lot of programming languages are available in the market today, but why do people choose python over them? What made it different from other scirpting languages. So factors made it unique, as below: Software...

Shallow And Deep Copying
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): A shallow copy constructs a new compound object...

Machine Learning With Python
1. Course description: Machine Learning with Python has been designed for the provision of having strong hold in creating Machine learning algorithms with the base of Python. This has been preferred as...
J

Writing Simple programs in Python(cont.)
To start writing simple programs in Python, we have to know firstly the SW development process and then we also have to know a bit about the language in which we wish to code,in this case,python, to get...

File Handling in Python - Basic Concept
File (Flat) Handling in Python Types of files in python: 1: Text file: Stores data in the form of characters. Customarily used to store text/string data. 2: Binary file: Stores data in the form of bytes....
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