美文网首页程序员
常用python装饰器框架

常用python装饰器框架

作者: 进击的原点 | 来源:发表于2023-02-18 18:32 被阅读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"

相关文章

  • python 装饰器

    一、我们在python语言中常用@classmethod、@staticmethod这个装饰器,装饰器的作用简单来...

  • python--装饰器--测试程序运行次数以及程序运行时间

    python的装饰器应用极其广泛,在python--学习的章节有所描述,在这里写两个常用的装饰器。 测试程序运行次...

  • python 装饰器

    前言 装饰器常用于认证、日志。 环境 python3.6 正文 装饰器的效果:在不修改方法的情况下,额外增加方法的...

  • 一周工作学习总结(2017.09.01-2017.09.10)

    面试 一面:电话面试,面了一些Python基础知识,装饰器、迭代器、scrapy框架(公司主要用这个框架来写爬虫,...

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • python常用的装饰器

    Python中有很多装饰器(decorator),可以减少冗余代码。Decorator本质上也是函数,只是它的参数...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • Python中的装饰器

    Python中的装饰器 不带参数的装饰器 带参数的装饰器 类装饰器 functools.wraps 使用装饰器极大...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

网友评论

    本文标题:常用python装饰器框架

    本文链接:https://www.haomeiwen.com/subject/mwebkdtx.html