Member-only story
5 real handy python decorators for analyzing/debugging your code
Apply these handy, general-purpose decorators directly to your code
The beauty of decorators is that they are really easy to apply but provide a lot of extra functionalities for your code. In this article we’ll go through 5 handy decorators that you can easily apply to real-world problems you’ll run into when debugging your code. We’ll check out decorators that help you:
- Time your function
- Performance check
- Repeater
- Ask you if you’re sure before executing
- wrap you function in a try-catch
The goal of this article is to offer you some ready-for-use decorators as well as inspire you to come up with some handy, general-purpose decorators.
Before we start: Did you know you can also make decorators keep track of state? Example: count the number of times a function was called so you can rate limit it. Make sure to read this article to understand how decorators work, how to apply them and when to use a decorator. In this article we explore decorators in 6 increasingly more complex steps.
1. Timer
Let’s start easy; we’ll start with a decorator that prints out the time it took for our function to run. This is the code:
Notice that our decorator itself is wrapped with @wraps(func). This is to make sure we pass our wrapped function. If we don’t do this wrapper.__name__
would just print ‘wrapper’ in stead of the function we’re actually decorating.
We’ll use this decorator on a function that calculates primes: