Create custom decorators in Python

Hello friends, we have learned how to define functions in Python. We know how to pass various data types as arguments, however, it is also possible for you to pass a function as an argument. In this tutorial, I will tell you how to create custom decorators in Python. You can check our previous post on the use of decorators and memoization in Python using decorators, to know more about it.

Create Custom Decorators in Python

I have defined two functions greetings() and my_desc(). These functions lack some common functionality. To add that functionality, I have created a decorator my_decorator(). This decorator takes functions as an argument.

def my_decorator(func):
    def wrapper():
        print("Hello I'm Codespeedy.")
        func()
        print("Contact me @+91 8001-007-659.")
    return wrapper

@my_decorator
def greetings():
    print("We can turn your idea into digital reality.")

@my_decorator
def my_desc():
    print("We provide digital and tech solutions for businesses. Our team is always committed to fulfill your requirements.")

greetings()
print('---------------------------------------------------------------------------------------------------')
my_desc()

I have created a wrapper function called wrapper() for my decorator. Now when my functions and decorators are ready, I want to wrap my decorator to each of my functions. For this, I have called it before my functions using the ‘@’ symbol. This enabled me to add functionalities to my functions.

Output :

Hello I'm Codespeedy.
We can turn your idea into digital reality.
Contact me @+91 8001-007-659.
---------------------------------------------------------------------------------------------------
Hello I'm Codespeedy.
We provide digital and tech solutions for businesses. Our team is always committed to fulfill your requirements.
Contact me @+91 8001-007-659.

Thus you can now successfully fabricate your custom decorators in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *