1 min read

Python Decorators

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.

Basic Decorator

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

say_whee()

Decorators with Arguments

If the function being decorated takes arguments, the wrapper function needs to accept them.

def do_twice(func):
    def wrapper_do_twice(*args, **kwargs):
        func(*args, **kwargs)
        func(*args, **kwargs)
    return wrapper_do_twice

@do_twice
def greet(name):
    print(f"Hello {name}")

greet("World")

Returning Values

Ensure the wrapper returns the value of the decorated function.

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before")
        val = func(*args, **kwargs)
        print("After")
        return val
    return wrapper

programming/python/python