A function can be defined under another function and function can also return another function: Nested function

Learn about Python closures to know in detail about nested function and enclosing scope.

How to create Python decorators?

So, now finally let’s dig into how to actually create Python decorators.

A decorator is just a callable that takes a function as an argument and returns a replacement function. Anything that implements __call__() function behind the scene is called callable and decorator is one of them.

Previously we mentioned that with decorators we can extend the functionality of a function without actually modifying it. Let’s see and implement this in a program.

As you can see in above example, we have created a decorator where we have passed the function display as an argument to the decorator function. The decorator function adds an extra functionality to that function and returns the result.

Notice that the original function is not changed.

Hence, this feature of adding extra functionality to a function without actually modifying it is called decorator in Python.

But this is not the how the decorators are syntactically implemented in Python. This was just to make you understand the working mechanism of a decorator.

Here is the proper implementation of decorator in a Python program.

Python Decorator’s Syntax

The decoration occurs in the line just before the function. The symbol ‘@’ is followed by the decorator functions name.

Here is the implementation of decorator in the example we example above.