python 7个好用的装饰器分享

1、dispach python 天然支持多态,但使用 dispatch 可以让你的代码更加容易阅读。
安装:
pip install multipledispatch 使用:
>>> from multipledispatch import dispatch>>> @dispatch(int, int)... def add(x, y):... return x + y>>> @dispatch(object, object)... def add(x, y):... return %s + %s % (x, y)>>> add(1, 2)3>>> add(1, 'hello')'1 + hello' 2、click click 可以很方便地让你实现命令行工具。
安装:
pip install click 使用:demo2.py :
import click@click.command()@click.option('--count', default=1, help='number of greetings.')@click.option('--name', prompt='your name', help='the person to greet.')def hello(count, name): simple program that greets name for a total of count times. for x in range(count): click.echo(fhello {name}!)if __name__ == '__main__': hello() 运行结果:
❯ python demo2.py --count=3 --name=joihhello joih!hello joih!hello joih!❯ python demo2.py --count=3your name: somenzzhello somenzz!hello somenzz!hello somenzz! 3、celery 分布式的任务队列,非 celery 莫属。
from celery import celeryapp = celery('tasks', broker='pyamqp://guest@localhost//')@app.taskdef add(x, y): return x + y 4、deprecated 这个相信大家在使用别的包时都遇到过,当要下线一个老版本的函数的时候就可以使用这个装饰器。
安装:
pip install deprecated 使用:demo4.py
from deprecated import deprecated@deprecated (this function is deprecated, please do not use it)def func1(): passfunc1() 运行效果如下:
❯ python demo4.pydemo4.py:6: deprecationwarning: call to deprecated function (or staticmethod) func1. (this function is deprecated, please do not use it) func1() 5、deco.concurrent 安装:
pip install deco 使用 deco 就像在 python 程序中查找或创建两个函数一样简单。我们可以用 @concurrent 装饰需要并行运行的函数,用 @synchronized 装饰调用并行函数的函数,使用举例:
from deco import concurrent, synchronized @concurrent # we add this for the concurrent functiondef process_url(url, data): #does some work which takes a while return result@synchronized # and we add this for the function which calls the concurrent functiondef process_data_set(data): results = {} for url in urls: results[url] = process_url(url, data) return results 6、cachetools 缓存工具
安装:
pip install cachetools 使用:

TPS56x201/8直流降压器的特点性能介绍
华为向联发科采购的芯片数量比以往大涨300%
新花样!机器人公司可地面行走的无人机
74ls181引脚图及功能_逻辑功能及特性
1月29日!赛思将亮相央视财经频道《新型工业化之路——专精特新》节目
python 7个好用的装饰器分享
298.2亿美元的机器人市场,为什么过得有点“惨”?
AMD 将于 2028 年在印度投资 4 亿美元,建设其最大的设计中心
基于FPGA的数字电路设计
京东方175亿LCD厂遭质疑:未投产已落后两代半
智慧园区需要什么样的数字化网络?
声智成功入选2021年度北京民营企业“中小企业百强”榜单
涡轮增压器的组成部分_涡轮增压器多久清洗一次
5G小基站拓展垂直行业市场大空间
铁丝防护网@享受自己辛福有价值生活
锂电池万能充电器,Lithium-Ion Battery Charger
我国首次超越韩国成为全球最大半导体设备市场
鸿蒙系统支持机型名单
质子交换膜燃料电池应用
双核Cortex-M4 32 位低功耗微控制器主要特性包括哪些?