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.
- Function Decorators in Python | Set 1 (Introduction)
- Decorators in Python
- Decorators with parameters in Python
- Memoization using decorators in Python
- Useful cases to illustrate Decorators in python
- Nested Decorators in Python
- Chain Multiple Decorators in Python
- Python Decorators: A Complete Guide
- Debugging decorators in Python
- How to preserve Function Metadata while using Decorators?
- Using else conditional statement with for loop in python
- Python - Conditional String Append
- Python - Conditional Prefix in List
- Conditional Inheritance in Python
- Python - Length Conditional Concatenation
- Conditional operation on Pandas DataFrame columns
- NLP | Storing Conditional Frequency Distribution in Redis
- Mahotas – Conditional Dilating Image
- Mahotas – Conditional Eroding Image
- Mahotas – Conditional Watershed of Image
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.