Introducing decorators
Decorators are the single most unfortunately explained language feature of Python. An improved way to teach decorators was presented by Steve Ferg on his blog: http://pythonconquerstheuniverse.wordpress.com/2012/04/29/python-decorators/. I've adapted his suggestions for use in this section.
Decorators associate setup and teardown functionality with some callable object. In the preceding example, we associated the functionality of "each time some function is called, it can be undone as a single block" with the makefoot
function. There is no way to call makefoot
without this new behavior added by the decorator.
Explaining decorators
I find it easiest to explain decorators by working from very basic Python and eventually ending with the funky @
line that goes above a function.
In Python, anything with a __call__
method is known as a
callable. Functions are one type of callable. There is basically no difference between calling something directly, and invoking its __call__...