I really like decorators in Python and I sometimes miss them when working in other languages. Today at work it hit me when I was working on a CoffeeScript project. It is really easy to implement Python-like decorators cleanly in CoffeeScript.
If you are not familar what decorators are in Python you should skim through this and this. In short they are a nice syntax for wrapping functions/methods with other functions in Python.
Decorators in Python
Here’s an example usage of Python decorator. Let’s pretend that this is a class for reading values from some device. It will give us values between 0 and 100, but in this app we want put a roof for the values it gives. We can create a decorator that limits the values given by the getter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
Decorators in CoffeeScript
So that was an advanced configurable decorator for Python. Lets see how CoffeeScript handles the same situation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Wow! That is a lot less syntax and no extra nesting!
This really shows how powerful anonymous functions and implicit returns are in CoffeeScript. Also the usage syntax would not be so clean if CoffeeScript didn’t have ability to call functions without the parenthesis.
The usage syntax is though better in Python, because you can stack decorators cleanly with it.
1 2 3 4 5 |
|
In CoffeeScript must put them after each others which can get nasty if you have many decorators.
1 2 3 |
|
But wait! There were no specific decorator syntax in Python in the old days. One could apply decorators just by calling it to the target and replacing the original method.
1 2 3 4 5 6 |
|
So you can do this in CoffeeScript
1 2 3 4 5 6 |
|
Pretty ugly, yeah, but might be better if you have tons of decorators.