We have created a simple decorator – a function which accepts another function as its only argument, prints some details, and returns a function or other callable object.
Well … you could say … we wrote so many lines of code just to print two other lines? Where is the simplicity or convenience in this approach?
Well … we could say … you should look at the following syntactic sugar:
As you can see, the definition of the simple_hello()
function is literally decorated with '@simple_decorator' – isn't that a nice syntax?
This means that:
- operations are performed on object names;
- this is the most important thing to remember: the name of the simple_function object ceases to indicate the object representing our
simple_function()
and from that moment on it indicates the object returned by the decorator, the simple_decorator.
The implementation of the decorator pattern introduces this syntax, which appears to be very important and useful to developers. That is why decorators have gained great popularity and are widely used in Python code. It should be mentioned that decorators are very useful for refactoring or debugging the code.