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
If you are not familar what decorators are in Python you should skim through
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.
Decorator in Python (decorator_example.py)download
#!/usr/bin/env python# Our magic deviceimportrandomdefroof(amount):defdecorator(method):defwrapper(*args):value=method(*args)ifvalue>amount:returnamountelse:returnvaluereturnwrapperreturndecoratorclassDevice(object):@roof(50)defget_value(self):# Read value from the devicereturnrandom.randint(0,100)if__name__=='__main__':reader=Device()foriinrange(10):printreader.get_value()
Decorators in CoffeeScript
So that was an advanced configurable decorator for Python. Lets see how
CoffeeScript handles the same situation.
Decorator in CoffeeScript  (decorator_example.coffee)download
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.
Stacking decorators in Python
classDevice(object):@roof(50)@floor(10)# Checks the bottom of the valuedefget_value(self):returnrandom.randint(0,100)
In CoffeeScript must put them after each others which can get nasty if you have