当前位置:网站首页>Seven easy-to-use decorators
Seven easy-to-use decorators
2022-06-11 04:11:00 【somenzz】
Share seven useful decorators , Convenient code .
1、dispach
Python Nature supports polymorphism , But use dispatch Make your code easier to read .
install :
pip install multipledispatchUse :
>>> 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 You can easily implement command-line tools .
install :
pip install clickUse :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()Running results :
* 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
Distributed task queues , Not Celery Perhaps judge of particulars, .
Celery Introduction and detailed usage , We can refer to the previous article :
Under development environment , How to use a command to make fastapi and celery Working together
One article celery Task remote invocation
from celery import Celery
app = Celery('tasks', broker='pyamqp://[email protected]//')
@app.task
def add(x, y):
return x + y4、deprecated
I believe you have encountered this problem when using other packages , You can use this decorator when you want to offline an old version of a function .
install :
pip install DeprecatedUse :demo4.py
from deprecated import deprecated
@deprecated ("This function is deprecated, please do not use it")
def func1():
pass
func1()The operation effect is as follows :
* 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
install :
pip install decoUse DECO As in the Python Finding or creating two functions in a program is as simple as . We can use @concurrent Decorate functions that need to run in parallel , use @synchronized Decorate functions that call parallel functions , Use examples :
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
Caching tools
install :
pip install cachetoolsUse :
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
Retry decorator , Support various retry requirements .
install :
pip install tenacityUse :
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 ExceptionLast
This article shares seven useful decorators , Hope to help you write code .

边栏推荐
- 人与人的一些不同
- Eth relay interface
- 三层带防护内网红队靶场
- 零时科技 | Discover 闪电贷攻击事件分析
- Detailed explanation of network time synchronization (NTP network timing) of video monitoring system
- WPF of open source project hero alliance
- Management system of College Students' associations based on SSM
- Evil CSRF
- MAUI 遷移指南
- golang泛型:generics
猜你喜欢

SSLStrip 终极版 —— location 劫持

6. 表格标签

6. form label

强烈推荐这款神器,一行命令将网页转PDF!

Guanghetong LTE Cat4 module l716 is upgraded to provide affordable and universal wireless applications for the IOT industry

Watson K's Secret Diary

Pci/pcie related knowledge

SQL注入关联分析

7. 列表标签

Cloud broadcast alert, guanghetong helps intelligent camera to build a "river protection" drowning prevention system
随机推荐
Management system of College Students' associations based on SSM
Esp32 porting lvgl
FreeRTOS startup - based on stm32
clickjacking漏洞的挖掘与利用
Market prospect analysis and Research Report of pipe and hose press fitting tools in 2022
Why does the hospital comprehensive security system synchronize the NTP clock of the network server?
Guanghetong LTE Cat4 module l716 is upgraded to provide affordable and universal wireless applications for the IOT industry
A. Prefix range (C language)
Maui migration guide
Quartz: an old and robust open source task scheduling framework, which is smooth enough to use
Eth Of Erc20 And Erc721
unforgettable moments
Pictures that make people feel calm and warm
Market prospect analysis and Research Report of welding laser in 2022
Vulkan-官方示例解读-RayTracing
AI助力,释放法务势能!iTerms合同智审系统重磅发布
Composition and configuration of GPS Beidou clock synchronization (satellite time synchronization system) in power plant
再聊数据中心网络
Unity prefab scene 冲突合并工具 UnityYAMLMerge
This artifact is highly recommended. One line command will convert the web page to PDF!