Module (39%)
Section (23%)

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.


Code

def simple_decorator(function):
print('We are about to call "{}"'.format(function.__name__))
return function


@simple_decorator
def simple_hello():
print("Hello from simple function!")


simple_hello()
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×