Published: 03/04/2012 (Updated on 04/04/2012) with tags: Programming.
In Python, decorators are a construction that helps reduce boilerplate code, enhance the maintainability of our code and address the separation of concerns. A decorator is a statement just above the function it decorates. Here's a simple example so you can understand what I mean:
def heading1(func): """Define the decorating function - this wraps the return value of the string in html heading tags. Don't actually write html like this - it is a silly idea. """ def wrapper(*args, **kwargs): return "<h1>" + func(*args, **kwargs) + "</h1>" return wrapper # Use the decorator here, before the function definition. @heading1 def subject(): return "Decorators: A neat way to modify functions" print subject() # Output is "<h1>Decorators: A neat way to modify functions</h1>"
That seems very neat, but this is a simple way of writing something complicated, so there are some kinks to iron out.