Decorators in Python

Using decorators you can modify functions using other functions. If tou don’t want to modify a function but want to add to it more functionality then decorators is a god way to achieve that.

Example:

def decor(func):
    def wrap():
        print("***************")
        func()
        print("***************")
    return wrap

def print_text():
    print("Python is cool!")

decorated = decor(print_text)
decorated()

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
***************
Python is cool!
***************
ddn_ro@linux:~/Desktop$

Explanations:

We defined a function named decor that has a single parameter func.
Inside decor, we defined a nested function named wrap.
The wrap function will print a string, then call func(), and print another string.
The decor function returns the wrap function as its result.

The variable decorated is a decorated version of print_text. We replace print_text with its decorated version, so print_text = decor(print_text).

In our previous example, we decorated our function by replacing the variable containing the function with a wrapped version. This pattern can be used at any time, to wrap any function.

Python provides support to wrap a function in a decorator by pre-pending the function definition with a decorator name and the @ symbol.

If we are defining a function we can “decorate” it with the @ symbol. This will have the same result as the above code.

Example:

def decor(func):
    def wrap():
        print("***************")
        func()
        print("***************")
    return wrap

@decor
def print_text():
    print("Python is cool!")

print_text();

The terminal output is exactly the same as the preceded code.

Note:
A single function can have multiple decorators.

Leave a Reply