David - Musings of an SRE

Understanding Python Decorators

Decorators are functions that replaces an existing function with another function with the original function as a parameter.

A decorator function would have the following structure:

def decorator_name(func):
  def func_wrapper(*args)
    return "any content" + str(*args)
  return func_wrapper

Sometimes, you might see functions that are defined like:

@some_function
def do_stuff(*args):
  return str(*args)

@some_function in this case is a decorator.

What the above actually translate to in pseudo-code is:

Whenever do_stuff() is called, return the output of some_function() which takes in the output of do_stuff().

An example of how it can be used would be something like:

Python Decorators Example

If there’s one thing you ultimately need to understand about decorator functions, it is that it always have to return a function.

References: