The Tech Buffet #10: 12 Python Decorators to Take Your Code to the Next Level
Do more things with less code without compromising on quality
Hello, this is Ahmed! 👋
This issue is part of a Python series dedicated to sharing tips and best practices to improve your code.
If you’re interested in this type of content (+ the additional coding material)
consider subscribing.
Python decorators are powerful tools that help you produce clean, reusable, and maintainable code. They provide interesting functionalities such as caching, automatic retry, rate limiting, logging, or turning your classes into supercharged data containers.
I’ve long waited to learn about these abstractions and now that I’ve acquired a solid understanding, I’m writing this practical guide to help you, too, grasp the concepts behind decorators.
No big intros or lengthy theoretical definitions today.
This issue is rather a documented list of 12 helpful decorators I regularly use in my projects to extend my code with extra functionalities.
We’ll dive into each decorator, look at the code, and play with some hands-on examples.
If you’re a Python developer, this post will extend your toolbox with helpful scripts to increase your productivity and avoid code duplication.
Less talk, I suggest we jump into the code now 💻.
1 — @logger (to get started)✏️
If you’re new to decorators, you can think of them as functions that take functions as input and extend their functionalities without altering their primary purpose.
Let’s start with a simple decorator that extends a function by logging when it starts and ends executing.
The result of the function being decorated would look like this:
To write this decroator, you first have to pick an appropriate name: let’s call it logger.
logger is a function that takes a function as input and returns a function as output. The output function is usually an extended version of the input. In our case, we want the output function to surround the call of the input function with start
and end
statements.
Since we don’t know what arguments the input function uses, we can pass them from the wrapper function using *args and **kwargs. These expressions allow passing an arbitrary number of positional and keyword arguments.
Here’s a simple implementation of the logger
decorator:
Now you can apply logger to some_function
or any other function for that matter.
decorated_function = logger(some_function)
Python provides a more Pythonic syntax for this, it uses the @ symbol.
11 decorators left to review. Let’s move to the next one.
Keep reading with a 7-day free trial
Subscribe to The Tech Buffet to keep reading this post and get 7 days of free access to the full post archives.