45. Python Decorators

I have been learning about Flask and managed to build some interesting application that are in my portfolio now. 

With this occasion, I learned about Decorators in Python. 

The first meeting with the decorators was quite confusing. I remember the first time I was trying to decipher what was happening in front of my eyes.

My mind was trying to attach itself to something, a bit of meaning, but it was getting lost. I still cannot say that I can provide the correct answer to what the final output would be, if I look at a decorated function. 

For some reason, this is confusing for me. So here I am writing about it. 

These decorator functions wrap themselves around another functions (the innies * if you know what I mean*) and they add functionalities. 

That is possible because of the “closure” principle in Python. Closure makes it possible for the inner function to remember the scope of the outer function, to access and modify the state of it. 

def outer_function(message):

    def inner_function():

        print(f"Message from closure: {message}")

    return inner_function

 

closure_function = outer_function("Hello, closures!")

closure_function()

# Output: Message from closure: Hello, closures!

Why is this possible ? Because in Python, functions are first class citizens - they are treated like any other object, they support operations like being passed as arguments, returned from functions and assigned to a variable. 

 

When creating a decorator, the inside function, the one which gets decorated is the closure.  

So in my Flask case, the outer function  @app.route(“ ”)  decorates whatever function gets attached to. 

@app.route(“ ”)

def innie():

    #things to happen

 

This is a very simple explanation. I found a good article here where you can find a lot of examples if needed.

 

*innies - reference to the series “Severance”