Fun with Decorators
First and foremost, Python is a fantastic language. I recently found myself explaining decorators in Python and have been thinking up any and all ways to use them. For those that aren't familiar with decorators, they are an implementation of a particular software design pattern allowing a programmer to add functionality to existing methods or classes:
Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
In Python, decorators often have the following definition:
They can then be called using one of two methods:
The preferred syntax currently is the 'implicit' method, making the most of the neater '@'. Given this pattern, we can implement all sorts of fun stuff in our code. For example, haven't you always wanted to count how many times a particular function might get called in your code? Well take a look at this basic implementation:
You'll now have a dictionary with a count of how often certain functions in your codebase have been executed. Obviously this is a fairly naive implementation, but you can see from this example, just how simple, yet powerful decorators can be. Take a look at this simple timer wrapper for your functions:
I think you now get the point. Whilst this may at first seem trivial, I think you can now appreciate that this is a particularly powerful construct in a language. I hope you start using decorators more often, just like I did!