create a decorator for a function in python

A decorator is a design pattern that allows a user to add new functionality to an existing object or function without modifying its structure. In Python, a decorator is a callable that takes a callable as input and returns another callable. Here is an example of how to create a decorator for a function in Python:

main.py
def my_decorator(func):
    def wrapper():
        print("Before the function is called.")
        func()
        print("After the function is called.")
    return wrapper

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

say_hello()
# Output:
# Before the function is called.
# Hello!
# After the function is called.
321 chars
17 lines

In the example above, we define a decorator my_decorator that takes a function func as input and returns a new function wrapper. The wrapper function adds some additional behavior before and after calling the original function func.

We then decorate the function say_hello by adding @my_decorator before its definition. This is equivalent to calling say_hello = my_decorator(say_hello).

When we call say_hello(), the Python interpreter automatically calls my_decorator(say_hello)() which returns the wrapper function. We then call the wrapper function which prints "Before the function is called.", calls the original say_hello function, and prints "After the function is called."

related categories

gistlibby LogSnag