Select Page

Browsing through the code for a Flask app I noticed the symbol that I had seen many times before only now I had to know finally, “what are decorators in Python?

The Idea of a Wrapper

Decorators in Python modify the functions they decorate. They are never to be the same again. Here the regular function that just prints and ceases to exist is made into something entirely new.

The idea of First Class objects in a programming language is a concept itself and Python supports it. One example of this concept in Python is functions. Functions can be assigned to variables and they can be passed as parameters to other functions. Finally, functions can be returned by other functions.

What does that mean? It means functions in Python are the same as any other object in that they can be used in the same way.

def add_extra_stuff(func):
    def arbitrary_func():
        print("I'm executing, go fish!")

@add_extra_stuff
def undecorated_func():
    print("I was told I'd be a regular ol' Python function.")

# tough luck undecorated_func ! you aren't executing today.
undecorated_func()

Executing the code above results in the output: “I’m executing, go fish!”

Why is that?

To demonstrate what’s happening focus on this example below. The two scripts have identical results when executed.

def add_extra_stuff(func):
    def arbitrary_func():
        print("I'm executing, go fish!")

def undecorated_func():
    print("I was told I'd be a regular ol' Python function.")

new_func = add_extra_stuff(undecorated_func)

new_func()

The output for this code is the same, “I’m executing, go fish!”.

Decorators simplify the whole process and act as wrappers to functions they decorate. It’s all about the time-savings and simplification when it comes to Python. What about performance you say? There is always Go.

error: