Function Decorators in Python

In this tutorial we want to learn about Function Decorators in Python, first of all let’s talk about function decorators.

 

 

What is Function Decorators in Python?

Function decorators are powerful functions for modifying and enhancing the behavior of functions. using decorators you can add functionality to a function without changing its source code. You can use decorators for different purposes, for example from logging to memorization to performance profiling. you can create decorators in different ways.

 

 

 

First Way for Creating Function Decorators

The first way of creating decorators is to use randomization. for example you want to create a decorator that randomly modifies the output of a function. 

In this example random_decorator randomly converts the output of the greet function to uppercase or lowercase.

 

 

 

This will be the result

Function Decorators in Python
Function Decorators in Python

 

 

 

Second Way for Creating Function Decorators

Another way for creating Python decorators is to use external APIs or services. for example, you want to create a decorator that adds random image or quote to the output of functions by calling an external API. 

In this example random_image_decorator calls Unsplash API to retrieve random landscape image and adds it to the output of the greet function. 

 

 

 

 

More Examples on Function Decorators

Now let’s create some more examples about this concept in Python

 

Example 1: Logging Decorator
A common use of decorators is to log the function calls and their arguments.

 

 

 

Example 2: Timing Decorator
You can create a decorator to measure the execution time of a function.

 

 

 

Example 3: Caching (Memoization) Decorator
You can create a decorator to cache the results of expensive function calls.

 

 

 

So we can say that Function decorators in Python are powerful for extending the functionality of functions without modifying their source code. 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×