DEV Community

Cover image for Python Intermediate: How to use Python Decorators.
Tahuruzzoha Tuhin
Tahuruzzoha Tuhin

Posted on • Edited on

Python Intermediate: How to use Python Decorators.

Python decorators

Python has an intriguing feature called decorators that allows you to add functionality to existing programs. This is also known as metaprogramming since a portion of the program attempts to alter another portion of the program during the compilation process. Learning requirements for decorators: To comprehend decorators, we must first grasp a few fundamental Python concepts.

We must be comfortable with the reality that everything in Python is an object (yes, including classes). The names we provide to these things are merely identifiers. Functions are not exceptions; they are also objects (with attributes). Different names can be assigned to the same function object.

Example:

def function(value):
   print(value)

function("Enablegeek")

second = function
second("Enablegeek")
Enter fullscreen mode Exit fullscreen mode

Output:

Enablegeek
Enablegeek

Enter fullscreen mode Exit fullscreen mode

The output from the first and second functions is the same when the code is executed. The first and second names in this case correspond to a similar function object. Things are starting to become strange now. Functions can be provided to another function as parameters. If you’ve used Python functions like map, filter, or reduce, you’re already aware of this. Higher-order functions are functions that accept other functions as parameters. Here’s an example of a function like this.

Example:

def Additive(item):
   return item + 10


def Substructive(item):
   return item - 10


def Operator(func, x):
   result = func(x)
   return result

print(Operator(Additive, 100))
print(Operator(Substructive, 100))

Enter fullscreen mode Exit fullscreen mode

Output:

110
90

Enter fullscreen mode Exit fullscreen mode

Returning to Decorators, Callable functions and methods are those that can be called. Callable refers to any object that implements the special call() function. A decorator, in the most basic sense, is a callable that returns another callable. A decorator basically takes a function, adds some functionality to it, and returns it.

Example:

def Decorated_Function(func):
   def Internal():
       print("Decorated methods here!")
       func()
   return Internal


def Simple_Function():
   print("Ordinary methods here!")


Simple_Function()

Well_Decorated = Decorated_Function(Simple_Function)
Well_Decorated()

Enter fullscreen mode Exit fullscreen mode

Output:

Ordinary methods here!
Decorated methods here!
Ordinary methods here!

Enter fullscreen mode Exit fullscreen mode

The function Simple_Fuction() was decorated, and the resulting function was named Well_Decorated().

The decorator function, as we can see, provided some extra functionality to the original function. This is analogous to wrapping a present. The decorator serves as a container. The nature of the adorned object (the real present within) remains unchanged. However, it now appears to be attractive (since it got decorated).

In general, we decorate a function and rename it,

Example:

def Decorated_Function(func):
   def Internal():
       print("Decorated methods here!")
       func()
   return Internal


@Decorated_Function
def Simple_Function():
   print("Ordinary methods here!")

Simple_Function()
Enter fullscreen mode Exit fullscreen mode

Output:

Decorated methods here!
Ordinary methods here!

Enter fullscreen mode Exit fullscreen mode

Python Decorator Chaining

Python allows for the chaining of several decorators. This means that a function can be decorated several times with various (or the same) decorators. The decorators are simply placed above the required function.

Example:

def initialize(func):
   def internal(*args, **kwargs):
       print("$" * 30)
       func(*args, **kwargs)
       print("$" * 30)
   return internal


def hash_wise(func):
   def internal(*args, **kwargs):
       print("#" * 30)
       func(*args, **kwargs)
       print("#" * 30)
   return internal


@initialize
@hash_wise
def printer(msg):
   print(msg)


printer("Enablegeek is Awesome!")

Enter fullscreen mode Exit fullscreen mode

Output:

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
##############################
Enablegeek is Awesome!
##############################
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Enter fullscreen mode Exit fullscreen mode

This has been a long road! You began this session by learning more about functions, specifically how they may be defined inside other functions and handed around like any other Python object. Then you discovered decorators and how to write them.

You can also find the tutorial Python Decorators.

Top comments (1)

Collapse
 
shahimran profile image
Md. Shah Imran Shovon

great tutorial. Thanks