当前位置:网站首页>七个好用的装饰器
七个好用的装饰器
2022-06-11 04:03:00 【somenzz】
分享七个好用的装饰器,方便你撸代码。
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(f"Hello {name}!")
if __name__ == '__main__':
hello()运行结果:
* python demo2.py --count=3 --name=joih
Hello joih!
Hello joih!
Hello joih!
* python demo2.py --count=3
Your name: somenzz
Hello somenzz!
Hello somenzz!
Hello somenzz!3、celery
分布式的任务队列,非 Celery 莫属。
Celery 介绍和详细用法,可以参考前文:
开发环境下,如何通过一个命令让 fastapi 和 celery 一起工作
from celery import Celery
app = Celery('tasks', broker='pyamqp://[email protected]//')
@app.task
def add(x, y):
return x + y4、deprecated
这个相信大家在使用别的包时都遇到过,当要下线一个老版本的函数的时候就可以使用这个装饰器。
安装:
pip install Deprecated使用:demo4.py
from deprecated import deprecated
@deprecated ("This function is deprecated, please do not use it")
def func1():
pass
func1()运行效果如下:
* python demo4.py
demo4.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 function
def 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 function
def process_data_set(data):
results = {}
for url in urls:
results[url] = process_url(url, data)
return results6、cachetools
缓存工具
安装:
pip install cachetools使用:
from cachetools import cached, LRUCache, TTLCache
# speed up calculating Fibonacci numbers with dynamic programming
@cached(cache={})
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
# cache least recently used Python Enhancement Proposals
@cached(cache=LRUCache(maxsize=32))
def get_pep(num):
url = 'http://www.python.org/dev/peps/pep-%04d/' % num
with urllib.request.urlopen(url) as s:
return s.read()
# cache weather data for no longer than ten minutes
@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_weather(place):
return owm.weather_at_place(place).get_weather()7、retry
重试装饰器,支持各种各样的重试需求。
安装:
pip install tenacity使用:
import random
from tenacity import retry
@retry
def do_something_unreliable():
if random.randint(0, 10) > 1:
raise IOError("Broken sauce, everything is hosed!!!111one")
else:
return "Awesome sauce!"
@retry(stop=stop_after_attempt(7))
def stop_after_7_attempts():
print("Stopping after 7 attempts")
raise Exception
@retry(stop=stop_after_delay(10))
def stop_after_10_s():
print("Stopping after 10 seconds")
raise Exception
@retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
def stop_after_10_s_or_5_retries():
print("Stopping after 10 seconds or 5 retries")
raise Exception最后
本文分享了七个好用的装饰器,希望对你写代码有所帮助。

边栏推荐
- Fundamentals of embedded audio processing
- app直播源码,平台登录页面实现和修改密码页面实现
- Docker swarm installs redis cluster (bitnami/redis cluster:latest)
- 三层带防护内网红队靶场
- Management system of College Students' associations based on SSM
- After the college entrance examination, what can I do and how should I choose my major-- From the heart of a college student
- Guanghetong LTE Cat4 module l716 is upgraded to provide affordable and universal wireless applications for the IOT industry
- What great open source projects does Google have?
- Watson K's Secret Diary
- Esp32 porting lvgl
猜你喜欢

Large factory outsourcing or self research company? How to choose a job for a tester?

Code replicates CSRF attack and resolves it

Cloud broadcast alert, guanghetong helps intelligent camera to build a "river protection" drowning prevention system

Eth Transfer

Docker swarm installs redis cluster (bitnami/redis cluster:latest)

Pci/pcie related knowledge

Construction of esp8266/esp32 development environment

Simulation of radar emitter modulated signal

Detailed explanation of scenario method for common test case design methods

Chinese classics for children
随机推荐
Market prospect analysis and Research Report of pipe and hose press fitting tools in 2022
Programming battle -- challenging college entrance examination questions
域名解析耗时是什么?域名解析耗时影响因素有哪些?
FreeRTOS startup - based on stm32
Simulation of radar emitter modulated signal
图像检测相关模型数据格式
Safe and borderless, Guanghe tongdai 5g module +ai intelligent security solution shines at CPSE Expo
Market prospect analysis and Research Report of single photon counting detector in 2022
Vulkan-官方示例解读-Shadows(光栅化)
2022 love analysis · privacy computing vendor panoramic report | love Analysis Report
Market prospect analysis and Research Report of modular lithium ion battery in 2022
Google 有哪些牛逼的开源项目?
Exploitation and utilization of clickjacking vulnerability
Possible problems with password retrieval function (supplementary)
2022爱分析· 隐私计算厂商全景报告 | 爱分析报告
华生·K的秘密日记
如何检查域名解析是否生效?
Docker swarm installing MySQL Cluster
Guanghetong LTE Cat4 module l716 is upgraded to provide affordable and universal wireless applications for the IOT industry
[signalr complete series] Net6 Zhongshi signalr communication