decorator

What is decorator?

A decorator in Python is like a shortcut to modify or add extra behaviour to a function or method without changing its actual code.

def my_decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Output:

Before function  
Hello!  
After function  

The @my_decorator modified say_hello without touching its original code.

Updated on