What is a python decorator?

Mousse Anis
2 min readSep 7, 2021

--

A brief introduction to python decorators.

As a python programmer, sooner or later, you will come across the term ‘decorators’. Understanding and mastering decorators is a task that you should apply yourself to. This article will give you a smooth introduction to python decorators … steadfast and enjoy this article :)

A decorator can be helpful when used correctly (In my past articles on Data classes and static polymorphism, I used decorators extensively).

But first, we need to have an understanding of what a function is in python.

What are functions?

Functions are blocks that perform a defined action. They can have parameters and can also return data as a result. Some functions can also have side effects on top of the action they are supposed to perform.

Basic function

In python, functions are First-class objects. This means that they can be arguments or elements return by other functions, just like any built-in type/object(type, int, string, etc.…).

Functions as arguments and returning object of another function

Another cool feature with function is that you can create functions within another function. We call it nested functions.

nested functions

Decorator

Decorators were introduced with python 2.4 and are summarized by the PEP 318. (Python Enhancement Proposal or PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment)

Simply put, decorators are just functions that are warped on other functions and modify their behavior.

In the example below, we create a decorator called “time_it” which will print every function’s running time. “time_it” will be applied to an example function, “say_hi”.

simple decorator

Better syntax for Decorator

As you can see, the previous example can be pretty lengthy and confusing. Taking inspiration from the annotation in Java, python allows you to use a decorator via the “@” symbol.

The following example will leverage the “@” with our “time_it” decorator.

decorator using the @ syntax

And here it is, now you know how to create a simple python decorator.

In conclusion

So here we are, you can now receive your “decorator master” badge… wait, I might have jumped the gun here :).

There is more depth into decorators. In a follow-up article, we will dive a little deeper into the decorators. We will see how to chain multiple decorators, or pass some arguments to a decorator, what class decorators are, and much more.

Thank you for reading!

Missy, after understanding how decorators work.

--

--

Mousse Anis
Mousse Anis

Written by Mousse Anis

Ex Quant, now software engineer who loves to cook. Opinions/Views are my own

No responses yet