Sunday 17 May 2009
I created my first python decorator today, I have been using them for a while in cherrypy and others, but never have had to create my own. In my case I was using it to ensure that a method attribute was converted to an int before it hit the actual function, as the attribute could be passed as a string. Having several functions that had this behaviour creating a decorator seemed the best option rather than adding the conversion code to each function, that and I wanted to know how they worked. Decorators work by creating a function that returns a function (though they can be classes, anything callable I believe). The function that is returned is the one that is to be run rather than the one that was originally written, which in my book is kind of funky (and that's good funky). Once you have created a decorator function you can then just add @functionname to the top of your actual function and then the actual function becomes the function that you output in your decorator.