TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial…

Member-only story

Understanding Python decorators: Six levels of decorators from beginner to expert

Mike Huls
TDS Archive
Published in
6 min readJan 8, 2022

--

This code is pretty decorated already (image by Intricate Explorer on Unsplash)

Decorators are a very handy tool that can be used to change the behavior of a function without modifying the function itself. They allow you to easily add functionality without changing existing code. There are many use-cases (some of which we’ll get into today) like logging, performance checking, verifying permissions etc.

After this article you have a clear understanding how decorators work, how to apply them and when to apply them. We’ll start with the easiest, most basic example and then slowly work up our way to more complex ones. In the end we’ll have a function, decorated with multiple decorators of different types. Let’s code!

How decorators work

First we’ll specify a function that we want to decorate:

As you can see this function is called ‘sayhello’ and we can execute it by running sayhello()

--

--

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Mike Huls
Mike Huls

Written by Mike Huls

I write about interesting programming-related things: techniques, system architecture, software design and how to apply them in the best way. — mikehuls.com

Responses (2)