Decorators Python

I’ve come across decorators while using Flask and this is an attempt to better understand how they work.

Use of decorators can appear with an @ sign before a function definition. This line itself isn’t the decorator, but invokes the decorator.

A decorator is a function that takes a function in as an argument and returns a function.

Here is an example below.

def function1():
  print('hello')

def function2(func):
  def function3() :
    print('add something before')
    func()
    print('add something after')
  return function3


function1 = function2(function1)
function1()

In line 12, we see that function2 is modifying function1. Function1 originally just prints ‘hello’. If you call function1 in line 13, it will print ‘add something before’, ‘hello’, and ‘add something after’. Function2 is the decorator here.

def function2(func):
  def function3() :
    print('add something before')
    func()
    print('add something after')
  return function3

@function2
def function1():
  print('hello')

function1()

We can rewrite the previous line 12, with what we have in line 8 here. This acts in the same way and results in the same outcome. The @function2 is the decorator invocation line.

Some other resources: