Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Conditional Inheritance in Python
Next article icon

Conditional Decorators in Python

Last Updated : 10 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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


Next Article
Conditional Inheritance in Python

V

vanshikagoyal43
Improve
Article Tags :
  • Python
  • Python Decorators
Practice Tags :
  • python

Similar Reads

  • call() decorator in Python
    Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modifie
    3 min read
  • Decorators in Python
    In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
    10 min read
  • Closures And Decorators In Python
    Closures and decorators are powerful features in Python that allow for more advanced and flexible code patterns. Understanding these concepts can greatly enhance your ability to write clean, efficient, and reusable code. Why Python decorators rather than closures?Python decorators are preferred over
    3 min read
  • Chain Multiple Decorators in Python
    In this article, we will try to understand the basic concept behind how to make function decorators and chain them together we will also try to see Python decorator examples.  What is Decorator In Python?A decorator is a function that can take a function as an argument and extend its functionality a
    2 min read
  • Conditional Inheritance in Python
    It happens most of the time that given a condition we need to decide whether a particular class should inherit a class or not, for example given a person, if he/she is eligible for an admission in a university only then they should be a student otherwise they should not be a student. Let's consider
    3 min read
  • Python Logical Operators
    Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss l
    6 min read
  • Iterators in Python
    An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration. __iter__(): __iter_
    3 min read
  • Conditional Statements in Python
    Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations. If Conditional Statement in PythonIf statement is the simplest form of a conditional st
    6 min read
  • Python 3 - Logical Operators
    Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False
    4 min read
  • Comparison Operators in Python
    Python operators can be used with various data types, including numbers, strings, boolean and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences