In Python, decorators are a construction that help 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. The first is that in a generally applicable decorator, the decorating function must be able to accept an arbitrary argument list (meaning any arrangement of arguments and keyword arguments). The issue with this is that the resulting decorated function takes on the signature of the decorating function, so introspection of the function tells you that it accepts ...Read more