This could be a huge performance booster for functions that do expensive processing (e.g. Subsequent invocations with the same parameters return the cached result. The decorator remembers the result of the first invocation of a function for a particular set of parameters and caches it.
They are used a lot, and it was really cumbersome to apply them without the decorator syntax. Static and class methods are useful when you don't have an instance in hand. Print 'I have no use for the instance or class' These decorators turn a class method correspondingly to a static method (no self first argument is provided) or a class method (first argument is the class and not the instance). The classic examples are the built-in and decorators.
DIVE INTO PYTHON DOWNLOAD CODE
My goal here is to open your mind to the possibilities and introduce you to super-useful functionality you can add to your code immediately by literally annotating your functions with a one-liner. There are so many examples that I'm hard pressed to choose. See PEP-3129, which is pretty short and builds on top of all the concepts and ideas of function decorators. Class decorators appeared first in Python 3.0. See PEP-0318 for an interesting discussion on the history, rationale and the choice of the name 'decorator'. Once you start using them you'll discover a whole universe of neat applications that help keep your code tight and clean and move important "administrative" tasks out of the main flow of your code and into a decorator.īefore we jump into some cool examples, if you want to explore the origin of decorators a little more, then function decorators appeared first in Python 2.4.
This dry description doesn't do decorators justice. They are the most user-friendly *and* developer-friendly implementation of aspect-oriented programming that I've seen in any programming language.Ī decorator allows you to augment, modify or completely replace the logic of a function or method. Python decorators are one of my favorite Python features.