Decorators in Python
My Master’s thesis requires that I make heavy use of Python, especially decorators.
That is not what I meant.
Having used Java before, I was familiar with the Decorator pattern commonly used in OOP-heavy languages and thought nothing special of it in the case of Python. But I was a bit wrong due to confusingly similar terminology and the closeness of the underlying concepts. Even the Wikipedia page says that one should not confuse the decorator pattern with Python decorators.
While working on my thesis, going through some code with a mysterious @some_name
written above def some_function (x, y)
got me curious, and soon enough I discovered that it was a decorator. The idea was confusing at first but was quite interesting to understand!
This hinges on the notion that functions themselves are objects in Python and can be passed as parameters to other functions and returned from other functions. Wow.
There are enough code examples already on this topic so there’s no point in adding more to explain it, but to think of intuitively, there could be many cases in which we’d want to use decorators:
- there already exists a function meant to perform an operation (say, addition of two numbers) but we’d want to extend its functionality a bit (i.e. “decorate” it). For example, adding the statement “The sum of numbers x and y is: “ before the output of the
sum (x, y)
function by adding a@print_verbose
decorator to it - adding diagnostics to existing functions to track timing issues, by including time logging code before and after a function executes
- you’re using some other (open/closed-source) code but you’d want to add your own additional functionality to some parts without modifying the original code
- compatibility checks in functions to avoid errors
It really fascinates me to think of how simple the underlying idea is, and that someone actually decided to implement it for functions in addition to objects. But wait! Functions are objects in Python. Well…
People have so, so many proposals for decorator implementations as well. Amazing!