Decorators – a method of metaprogramming

The decorator syntax was explained in Chapter 3, Modern Syntax Elements – Below the Class Level, as a syntactic sugar for the following simple pattern:

def decorated_function(): 
    pass 
decorated_function = some_decorator(decorated_function)

This verbose form of function decoration clearly shows what the decorator does. It takes a function object and modifies it at runtime. As a result, a new function (or anything else) is created based on the previous function object with the same name. This decoration may be a complex operation that performs some code introspection or decorated function to give different results depending on how the original function was implemented. All this means is that decorators can be considered as a metaprogramming tool.

This is good news. The basics of decorators are relatively easy to grasp and in most cases make code shorter, easier to read, and also cheaper to maintain. Other metaprogramming tools that are available in Python are more difficult to understand and master. Also, they might not make the code simple at all.

We'll take a look at class decorators in the next section.