程序员

常用python装饰器框架

2023-02-18  本文已影响0人  进击的原点

整理记录一下常用的python装饰器框架代码,以后项目开发脚本中需要时,可以根据具体场景套用该框架。

  1. 运行时间记录装饰器
import time
from functools import wraps


def timeit(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f'{func.__name__} took {end - start:.6f} seconds to complete')
        return result
    return wrapper

@timeit
def process_data():
    time.sleep(1)

  1. 重复运行装饰器
from functools import wraps

def repeat(number_of_times):
    def decorate(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(number_of_times):
                func(*args, **kwargs)
        return wrapper
    return decorate

@repeat(5)
def dummy():
    print("hello")

dummy()
# hello
# hello
# hello
# hello
# hello
  1. 重试装饰器
import time
from functools import wraps


def retry(exception: Exception, tries: int = 3, delay: int = 1, backoff: int = 2):
    def decorator_retry(func):
        @wraps(func)
        def run_with_retry_police(*args, **kwargs):
            _tries, _delay = tries, delay
            while _tries > 1:
                try:
                    return func(*args, **kwargs)
                except exception:
                    print(f'操作失败!再{_delay}秒后再尝试…')
                    time.sleep(_delay)
                    _tries -= 1
                    _delay *= backoff
            return func(*args, **kwargs)
        return run_with_retry_police
    return decorator_retry


@retry(exception=ValueError, tries=3, delay=2)
def random_value():
    value = random.randint(1, 5)
    if value == 3:
        raise ValueError("Value cannot be 3")
    return value


  1. 统计运行次数装饰器

def countcall(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.count += 1
        result = func(*args, **kwargs)
        print(f'{func.__name__} has been called {wrapper.count} times')
        return result
    wrapper.count = 0
    return wrapper


@countcall
def process_data():
    pass
  1. singledispatch装饰器
    该装饰器允许一个函数对不同类型的参数有不同的实现。
from functools import singledispatch

@singledispatch
def fun(arg):
    print("Called with a single argument")

@fun.register(int)
def _(arg):
    print("Called with an integer")

@fun.register(list)
def _(arg):
    print("Called with a list")

fun(1)  # Prints "Called with an integer"
fun([1, 2, 3])  # Prints "Called with a list"
上一篇下一篇

猜你喜欢

热点阅读