In the post “Python decorators for dummies (me)” I’ve explained something about the python decorators. In the post there are theorical examples, in this post I want to show some real world use cases for the python decorators.

The very first use case is a timing decorator. I use it to compute the execution time of a function, for debugging and profiling purpose. It is a very simple decorator but it is also very useful. Before and after the execution of the decorated function, the decorator takes the time and then before returning, it prints out the execution time.

the output is as follows:

Another decorator I often use is the log decorator, it helps me debugging my apps.

to use the log decorator you have to instantiate your logger

and then you have to apply the decorator to your functions

After executing the script, you will have a file named ‘log_file.log’ with the following content:

Last interesting use case is the use of decorators as synchronizations for threads.
The decorator is really simple. It executes the decorated function only after it takes the lock, when the decorator function returns it releases the lock.

the execution of this script will output:

Non-synchronized threads evolve in parallel while synchronized threads execute one after the other.

And what are your favourite decorators?