Python decorators introduction and example for performances

Updated:

Introduction

In Python, a decorator is a special kind of function that can be used to modify the behavior of other functions or classes.

Decorators are a powerful feature of the language that allow you to add additional functionality to code without modifying the original code itself.

Decorators are defined using the @ symbol, followed by the name of the decorator function.

Example

@decorator_function 
def some_function(): 
    # function code here 

The decorator function can then modify the behavior of the function that follows it.

This can be useful for tasks such as adding additional logging or error checking to a function,
or for creating more concise and readable code by separating concerns into different functions.

Here's an example of a decorator function that logs the execution time of a function:

import time 
from functtools import wraps 
 
def performance(func: Callable) -> Callable: 
    # we wrap the function 
    @wraps(func) 
    def wrapper(*args: Tuple, **kwargs) -> None: 
        func_name = f"'{func.__name}'" 
        start_time = time.time() 
        result = func(*args, **kwargs) 
        end_time = time.time() 
        run_time = end_time - start_time 
        print(f"Execution time for the function {func_name}: {run_time:.3f} seconds") 
        return result 
    return wrapper 

This decorator can then be used to time any function by simply adding the @performance decorator above the function definition:

@performance 
def my_function(): 
    # function code here 

When my_function is called, it will automatically be timed and the execution time will be printed to the console.


You could be interested in

logo of the category: python-logo.svg PySpark connection to PostgreSQL ... errors and solutions

How to connect PySpark to PostgreSQL
2023-01-03

Enums in Angular templates

How to use enum in the html template
2019-01-21
WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland without 'Cloud'.