当前位置:网站首页>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 .

边栏推荐
- Market prospect analysis and Research Report of beam combiner in 2022
- Methods to detect whether PHP websites have been broken
- unforgettable moments
- Code replicates CSRF attack and resolves it
- Chinese classics for children
- Eth Of Erc20 And Erc721
- Sslstrip Ultimate - location hijacking
- Source insight 4.0 setting shortcut keys for comments and uncomments
- Matlab reports an error when trying to use * * * as a function problem, and tries to execute script PCA as a function:
- 【网络篇】套接字编程
猜你喜欢

Notes on redisson distributed lock usage

SQL注入关联分析

Composition and configuration of GPS Beidou clock synchronization (satellite time synchronization system) in power plant

Pictures that make people feel calm and warm

Guanghetong won the "science and Technology Collaboration Award" of Hello travel, driving two rounds of green industries to embrace digital intelligence transformation

Esp32 development -lvgl uses internal and external fonts

2022爱分析· 隐私计算厂商全景报告 | 爱分析报告

Discussion on the development trend of remote power management unit (Intelligent PDU)

人与人的一些不同

让人感到心灵平静,阳光温暖的图片
随机推荐
Market prospect analysis and Research Report of single photon counting detector in 2022
Watson K's Secret Diary
Google 有哪些牛逼的开源项目?
Several time synchronization methods of Beidou timing system (GPS timing equipment)
Pictures that make people feel calm and warm
Market prospect analysis and Research Report of pipe and hose press fitting tools in 2022
Composition and configuration of GPS Beidou clock synchronization (satellite time synchronization system) in power plant
AI助力,释放法务势能!iTerms合同智审系统重磅发布
Esp32 development -lvgl uses internal and external fonts
A. Prefix range (C language)
Detailed explanation of scenario method for common test case design methods
编程大作战 -- 挑战高考题
Safe and borderless, Guanghe tongdai 5g module +ai intelligent security solution shines at CPSE Expo
Eth Transfer
Market prospect analysis and Research Report of surround packing machine in 2022
2022爱分析· 隐私计算厂商全景报告 | 爱分析报告
[cnn]|differences between CNN and transformer
App live broadcast source code, platform login page and password modification page
Market prospect analysis and Research Report of seed laser in 2022
Go failing - expected ‘package‘, found ‘EOF‘