DEV Community

XZM27
XZM27

Posted on

Decorators part II

This is a continuation to the previous post decorators in python.
Previously we passed the function display into the decorator function. But what if the display function has some arguments that it takes?

def decorator_function(original_function):
    def wrapper_function():
        #do something before the function
        print("hello from wrapper")
        return original_function()
    return wrapper_function


#this works same as decorator_function(display)
@decorator_function
def display():
    print("hello from display")

display()
Enter fullscreen mode Exit fullscreen mode

Passing arguments into decorators
lets pass down some arguments in display and see what happens.

@decorator_function
def display(name, age):
    print(f"hello from {name}. I am {age} years old.")

display("Dev", 15)
Enter fullscreen mode Exit fullscreen mode

Output

TypeError: wrapper_function() takes 0 positional arguments but 2 were given
Enter fullscreen mode Exit fullscreen mode

It throws an error because right now the wrapper function cannot take any arguments. This can be fixed by using *args and **kwargs.

def decorator_function(original_function):
    def wrapper_function(*args, **kwargs):
        #do something before the function
        print("hello from wrapper")
        return original_function(*args, **kwargs)
    return wrapper_function


#this works same as decorator_function(display)
@decorator_function
def display():
    print(f"hello from {name}. I am {age} years old.")

display("Dev", 15)
Enter fullscreen mode Exit fullscreen mode

*args allows us to pass any number of positional arguments and **kwargs allows us to pass any number of keyword arguments into the wrapper_function. Now we can pass any number of arguments into our decorated function.
Output

hello from wrapper
hello from dev. I am 15 years old
Enter fullscreen mode Exit fullscreen mode

Thank you for reading and learning.

Top comments (0)