Python Decorator @ Erwin | 2023-12-14T13:20:00Z | 1 minute read | Update at 2023-12-18T11:44:37Z

Python decorator is just a Syntactic Sugar which can add a wrapper for functions.

In this post, I use a timming decorator to explain it.

import time
from functools import wraps

conf = True

def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if conf:
            start_time = time.time()
            result = func(*args, **kwargs)
            end_time = time.time()
            print(f"Function {func.__name__} took {end_time - start_time} seconds to run.", flush=True)
            return result
        else:
            return func(*args, **kwargs)
    return wrapper


@timing_decorator
def xxx(a, b, b):
    pass

Decorator is a function with the function to be decorated as parameter, and return decorated function. In this example, when call the function xxx, the wrapper function which is returned by timing_decorator(xxx) is called.

xxx(a ,b , c) = timing_decorator(xxx)(a, b, c) = wrapper(a, b, c)

@wraps(func) is used to keep the xxx’s document and attributes.

© 2020 - 2024 Li Yuanhao's Blog

Powered by Hugo with theme Dream.

avatar

Li Yuanhao's BlogJust do it

Social Links