DEV Community

chanduthedev
chanduthedev

Posted on

Decorators in python

Before learning decorators in python, lets check what is decorator in general.

As the name itself says, decorator means, decorating or wrapping. If we say, decorating a table means making the table more beautiful by adding/placing other things like flowers, lights etc. So decorating basically means adding/modify extra things to make things looks differently.

A similar way, in python, decorators means decorating or wrapping functions. We can add some more functionality before/after executing the actual function.

Let's see this with example.

Decorator example with no arguments:

# Normal function
def add_num():
    return 2 + 3

# Decorator function
def decorator_func(fun):
    def wrapper():
        res_str = f'Sum of 2 + 3 is '
        re = fun()
        return res_str + str(re)
    return wrapper
Enter fullscreen mode Exit fullscreen mode

Normal function call:

add_num()
Enter fullscreen mode Exit fullscreen mode

Output:
5

Decorator function call:

dec_result = decorator_func(add_num)
print(dec_result)
Enter fullscreen mode Exit fullscreen mode

Output:
Sum of 2 + 3 is 5

In Decorator function, we added an extra string value to make the result more clear. In this way decorators are very useful..

Instead of calling decorator function directly, we can use annotations by using @ symbol like below

@decorator_func
def add_num():
    return 2 + 3
Enter fullscreen mode Exit fullscreen mode

Normal function call with decorator annotation:

dec_annot_call = add_num()
print(dec_annot_call)
Enter fullscreen mode Exit fullscreen mode

Outout:
Sum of 2 + 3 is 5

Decorator example with arguments:

To pass arguments to the decorator function, we need to use keyword arg params *args and *kwargs like shown below.

# Decorator function with arguments
def decorator_func(fun):
    def wrapper(*args, **kwargs):
        res_str = f'Sum of {args[0]} + {args[1]} is '
        re = fun(*args, **kwargs)
        return res_str + str(re)
    return wrapper

# Decorator annotations for normal function with args
@decorator_func
def add_num(arg1, arg2):
    return arg1 + arg2

# Calling with args
dec_annot_call = add_num(8, 9)
print(dec_annot_call)
Enter fullscreen mode Exit fullscreen mode

Output:
Sum of 8 + 9 is 17

Top comments (0)