Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Decorator in Python, What is Decorator, how to define decorator, how to call decorator, what is @ symbol in python

Python Decorators

Python Decorators — Complete Guide With Examples

A decorator in Python is a special function used to add extra features to another function without modifying the original function code. Decorators are written using the @ symbol and provide a clean, readable way to apply function wrappers.

Why Decorators?

  • To add new functionality without editing the original function
  • To follow DRY (Don't Repeat Yourself)
  • To add logging, authentication, validation, performance monitoring, etc.
  • To make code cleaner and more maintainable

Important Concept: Functions Are Objects

In Python, a function has an address and can be stored in variables, passed to other functions, and returned from functions. This allows decorators to work efficiently.


Example 1 — Simple Decorator That Adds GST

def displaypricegst(func):        # decorator
    def func(p):
        print("Price with GST =", p + p * 0.20)
    return func

@displaypricegst
def displayPrice(price):
    print("Actual price =", price)

displayPrice(100)

Explanation:

  • @displaypricegst wraps displayPrice()
  • Original function prints actual price
  • Decorator adds GST functionality

Example 2 — Decorator With Additional Features

def funnew(func):             # adds new + old features
    print("world")            # new feature
    return func

def createnew(func):          # replaces old feature
    def innerfun():
        a = 100
        b = 200
        print(a * b)
    return innerfun

@funnew
def fun():
    print("hello")

fun()

@createnew
def addition():
    print(100 + 200)

addition()

Output Explanation:

  • funnew decorator: prints world before executing original function
  • createnew decorator: completely overrides the original function

Understanding Higher-Order Functions

A function that accepts another function or returns another function is called a higher-order function.

Example — Assigning Function to Variable

def addition(a=10, b=2):
    print(a / b)

addition()

add = addition     # assigning function to reference variable
add(10, 3)

Output:

  • Functions can be called using another name
  • Because functions are objects in Python

Passing Function as Argument

def incr(x):
    return x + 1

def cfun(func, x):        # func receives function address
    result = func(x)
    return result

data = cfun(incr, 20)
print(data)

Explanation:

cfun takes a function and a value → calls the function internally → returns result.


Returning Function From Another Function

def addmain():
    def add():
        print("hello")
    return add           # returning inner function

x = addmain()
x()

This demonstrates closure-like behavior where inner function is returned and executed later.


Decorator Example — Function Inside a Function

def fun_main(func):
    def inner():
        print("Inner")
        func()           # calling original function
    return inner

def scs():
    print("Outer")

s = fun_main(scs)
s()

Output:

Inner
Outer

Practical Decorator Example

def fun(func):          # decorator
    def inner(msg):
        print(msg, "inner")
    return inner

@fun
def fun2(msg):
    print(msg)

fun2("welcome")

Explanation:

  • @fun replaces fun2 with inner
  • No matter what fun2 contains, decorator controls output

Understanding Decorator Flow (Diagram)

@decorator
def function():
    pass

decorator(function)  ---> returns new function  ---> assigned back to function
This is why decorators allow modification of behavior without editing the actual function.

Real-Life Use Cases of Decorators

  • Authentication
  • Logging system
  • Performance monitoring
  • Access control
  • Input validation
  • Debugging tools

Advanced Decorator Template (Professional Format)

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before execution")
        result = func(*args, **kwargs)
        print("After execution")
        return result
    return wrapper

@decorator
def myfunc(x, y):
    return x + y

print(myfunc(10, 20))

Key Concepts Learned

  • Decorators wrap functions
  • Use @decorator_name syntax
  • Decorators can modify, replace, or extend function features
  • Functions are treated as objects
  • Can pass functions as arguments
  • Can return functions

Post a Comment

1 Comments

  1. def feeswithgst(func):
    def func(a,b):
    sports=2000
    print("fees is",(a+b+sports)+(a+b+sports)*0.18)
    return func
    @feeswithgst
    def fee(a,b):
    print("fees is",a,b)
    fee(10000,8000)

    ReplyDelete

POST Answer of Questions and ASK to Doubt