Python Decorators

Python Decorators #

Decorators are a means to extend the functionality of existing functions without directly modifying the code of the existing functions.

Decorators are those @... bits right before a function definition.

Design #

In design, decorators are functions that take other functions as arguments.

def some_decorator(func):
    def wrapper():
        <do something>
        return func()

    return wrapper

The snippet above represents a conventional decorator layout.

The major components include:

  • A function as an argument

  • A nested wrapper() function, which does something (such as logging or printing something related to the function argument), and then returning the function argument itself. What this means is the decorator does exactly what the provided function does, BUT it adds <do something>

  • The decorator function return the wrapper nested function.

Invocation #

Decorators are used simply by placing the decorator right before a function definition.

@some_decorator
def <some_function>():
    ...

^ In this instance, some_decorator() modifies the functionality of some_function()

A single function can be extended with multipled decorators.