Conditional Decorators in Python
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.
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.
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.