In Python, decorators are functions or classes that wrap around a function as a wrapper by taking a function as input and returning out a callable. They allow the creation of reusable building code blocks that can either change or extend behavior of other functions.
Conditional Decorators
Given a condition, the idea here is to execute code or basically wrap a function using a decorator if a certain condition is met or true. There are two ways by which we can use a decorator conditionally.
Method 1: When the decorator decides how to wrap a function
- In this case the function is passed to a decorator normally
- Then based on the condition the decorator decides what to do with the code
The following program passes a function normally to the decorator then if the given condition is true the program returns the string in uppercase and if it is false it returns it in lower case.
condition = True
def conditional_decorator(func):
def wrapper():
oldstring = func()
if condition:
newstring = oldstring.upper()
else :
newstring = oldstring.lower()
return newstring
return wrapper
@conditional_decorator
def func():
return 'geeKSfoRGEEks'
print (func())
|
Output:
'GEEKSFORGEEKS'
Method 2: In this, decorators are called only if a certain condition is met.
In the following program, the program takes user input to decide on the condition. If the user enters 1, the decorator is called and the string is returned in uppercase. If the user enters 2, again a decorator is called and the given string is returned in lowercase. Apart from this if any other number is entered the function is returned as it is without any modification.
def decorator1(func):
def wrapper():
oldstring = func()
newstring = oldstring.upper()
return newstring
return wrapper
def decorator2(func):
def wrapper():
oldstring = func()
newstring = oldstring.lower()
return newstring
return wrapper
cond = 1
if cond = = 1 :
@decorator1
def func():
return 'GeeksFORGeeKs'
elif cond = = 2 :
@decorator2
def func():
return 'GeeksFORGeeKs'
else :
def func():
return 'GeeksFORGeeKs'
print (func())
|
Output:
GEEKSFORGEEKS
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Jul, 2020
Like Article
Save Article