Tuesday, May 19, 2026

Python Material - Part - 22 - Decorator

What is a Decorator?

A decorator is a wrapper around a function — it adds extra functionality without changing the original function!

Think of it like: Sprinkling chocolate powder on coffee — The coffee is the same, but with extra decoration on top! 🍫

Basic Decorator example

def
surendra(func): # function తీసుకుంటుంది
def wrapper():
print(
"Before function runs")
func() # original function execute
print("After function runs")
return wrapper # wrapper return చేస్తుంది


@surendra
def students_info():
print(
"Meera sindhu")
print(
"Narendra Boyina")

students_info() # calling function


Advanced Decorator example:

from functools import wraps

"""A decorator that checks permission before allowing a function
to run — only authorized users can execute it!
"""

"""@wraps(func) makes sure the original function's identity is never lost
even after being wrapped by a decorator"""

def require_admin(func):
@wraps(func)
def wrapper(user_role):
if user_role != "admin": #Blocks anyone who is not admin
print("Access denied: Admins only")
return None
else:
return func(user_role) #Allows admin to run the function
return wrapper

@require_admin
def acess_tea_inventory(role):
print("Access granted to tea inventory")

acess_tea_inventory("user")# blocked
acess_tea_inventory("admin") # allowed

No comments:

Post a Comment