Why do we need wrapper function in decorators?

Viewed 5116

If I create a decorator like following:

def my_decorator(some_fun):
    def wrapper():
        print("before some_function() is called.")
        some_fun()
        print("after some_function() is called.")
    return wrapper

@my_decorator
def just_some_function():
    print("Wheee!")

Another decorator can be defined as:

def my_decorator(some_fun):
    print("before some_function() is called.")
    some_fun()
    print("after some_function() is called.")

@my_decorator
def just_some_fun():
    print("some fun")

Both decorators will work the same. What is the benefit of using "wrapper" function inside decorator. I didn't get the purpose.

3 Answers

Its already explained why to use wrapper function, out of curiosity I am just giving examples what we can do if we don't need a wrapper function.

Type 1

Return a small function which returns None or pass

def decorator_func(to_be_decorated_function):
    print("Logging IN: Currrently  in function")
    to_be_decorated_function()
    print("Logging OUT: Currrently  in function")

    def a(): None  # or def a(): pass

    return (a)

@decorator_func
def to_be_decorated_function():
    print('October 16, 2000')

to_be_decorated_function()
# equivalent to 
#to_be_decorated_function = decorator_func(to_be_decorated_function)

Type 2

This merely tears out the usage of decorators, and just a slight tweak.What if we don't return , as well not use callable object at all.

def decorator_func(to_be_decorated_function):
    print("Logging IN: Currrently  in function")
    to_be_decorated_function()
    print("Logging OUT: Currrently  in function")

@decorator_func
def to_be_decorated_function():
    print('October 16, 2000')

to_be_decorated_function  # notice I'm just using the object and not callable function
# equivalent to
#decorator_func(to_be_decorated_function)

Output from both the types

Logging IN: Currrently  in function
October 16, 2000
Logging OUT: Currrently  in function
Related