Python: Decorators

Decorators are functions that “wrap” around other functions, changing their behavior without changing the function it self. If you have not seen my Closure lesson, you might want to visit it first (Closure)

If you already read it, let us move forward. Let’s start by building a simple function that simply prints my name:

Now we need to build the decorator function. You may notice it is a Closure

Now let’s us the dec() (decorator) to alter what my_name() returns

By passing the function as a argument through the decorator function, my name is now printed out now with text above and below.

Now we can build another decorator function, and try it out. Notice the output differs from the output above.

Next, notice I can nest the decorator functions together

Now, instead of the syntax about, you can simply add the decorator name with a @ in front and it will apply the decorator.

In the second box, you will notice I can stack or nest the 2 decorators I made.

In my humble opinion as a Data Scientist, I think the nesting function would be the most usefulness out of this. Again, I am not a software engineer. They may have more of use for this functionality.

Leave a Reply