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 timedef 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_decoratordef long_running_task():    total = 0    for i in range(1, 10_000_000):        total += i    print("✅ Task Completed.")    return total# Call the functionlong_running_task()
 
 
✅ Task Completed.⏱️ Execution time: 1.0263 seconds
Out[23]:
49999995000000
 
In [28]:
import datetimedef 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_calldef 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_calldef 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_calldef 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


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...

10 Best Python IDEs
Python is a very popular programming language. It's open source and used today as scripting language, web development, mobile and desktop in many areas thanks to the endless modules options it has While...

Python Programming Introduction.
Introduction To Python What is Software? What are its types? Software is a set of instructions, data, or programs used to operate computers and perform specific tasks. It tells the hardware what to...
P

How to know if an object is iterable?
An object in python is said to be an iterable if it obeys one of the following two rules:- 1. Object must consist of __getitem__ method 2. Object must consist of __iter__ method. String objects generally...
S

Sudheer S

0 0
0
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