DEV Community

Tess Mueske
Tess Mueske

Posted on

Function Decorators in Python

Writing dry code is important. DRY is a handy acronym meaning Don't Repeat Yourself. Dry code is more legible and easily understood by others, making you a better developer! Dry code avoids boilerplate code, which is code that is written again and again without much change.

Decorators are a powerful resource for developers wanting to write dry code in Python. A decorator is a way to package code into a reusable function. They can be used before functions, classes, or methods. In this post, we'll be covering function decorators.

A decorator is a function that takes another function as an argument and returns a new function in its output.

How to make a decorator function

Decorators take in another function as an argument.

def function_1():
    print("Hi")

def function_2(_f_):
    #function_2 is the decorator!
    another_function() #continue reading below to see what this function is....

Enter fullscreen mode Exit fullscreen mode

Inside the decorator function, there's a second function called a wrapper function.

The wrapper function is a nested function, meaning it's a function inside of a function.

The wrapper function is what adds the desired behavior.

def example_decorator(function):
    def wrapper_function(parameter1):
        print("Start")
        val = function(parameter1)  # this calls the function passed to example_decorator
        print("End")
        return val

    return wrapper_function
Enter fullscreen mode Exit fullscreen mode

So, let's put it all together:

def example_decorator(function):
    def wrapper_function(parameter1):
        print("Start")
        val = function(parameter1) # this calls the function passed to example_decorator
        print("End")
        return val

    return wrapper_function

def print_hello(message):
    print(f"{message}")

print_hello = example_decorator(print_hello)
#^^the variable name (here it's print_hello) can be anything you want. This is called function aliasing.

Enter fullscreen mode Exit fullscreen mode

Then, when you call print_hello, you get....

print_hello("Hello"):
# Output: 
# Start
# Hello
# End

Enter fullscreen mode Exit fullscreen mode

Wooooo!

Reusability

When you want to re-use the function, you activate it at any point in your code using an 'at' symbol: @. The code beneath the @ is then run through the function we defined previously.

@example_decorator
def print_hello(message):
    print(f"{message}")

# Calling the decorated function:
print_hello("Hi")
# Output: 
# Start
# Hi
# End
Enter fullscreen mode Exit fullscreen mode

Whew, that was a lot!

Function decorators are a challenging part of coding in Python! This stuff is hard, and you are doing great. :)

Sources:
Flatiron School material
https://www.youtube.com/watch?v=BE-L7xu8pO4
https://www.youtube.com/watch?v=WpF6azYAxYg
https://www.youtube.com/watch?v=r7Dtus7N4pI

Top comments (0)