七个好用的装饰器
分享七个好用的装饰器,方便你撸代码。
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 莫属。
from celery import Celery
app = Celery('tasks', broker='pyamqp://guest@localhost//')
@app.task
def 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():
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 results
6、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
以上就是本次分享的所有内容,如果你觉得文章还不错,欢迎关注公众号:Python编程学习圈,每日干货分享,发送“J”还可领取大量学习资料。或是前往编程学习网,了解更多编程技术知识。
推荐阅读
使用VScode的几点感受,对比Pycharm、Jupyter优劣势
之前一直是PyCharm+Jupyter的组合,能满足几乎所有的Python开发需求。最近我开始用vscode,发现很香。PyCharm适合做项目开发,或者平常写写脚本,算是全能型IDE。但PyCharm体积大,对硬件消耗厉害,不够轻便。Jup...
Python技术大本营阅读 475
数据结构与算法:二分查找
一、常见数据结构简单数据结构(必须理解和掌握)有序数据结构:栈、队列、链表。有序数据结构省空间(储存空间小)无序数据结构:集合、字典、散列表,无序数据结构省时间(读取时间快)复杂数据结构树、 堆图二...
白鲸鱼赞 9阅读 5.3k
滚蛋吧,正则表达式!
你是不是也有这样的操作,比如你需要使用「电子邮箱正则表达式」,首先想到的就是直接百度上搜索一个,然后采用 CV 大法神奇地接入到你的代码中?
良许赞 3阅读 1.5k
搭个ChatGPT算法模型,从哪开始?
最近 ChatGPT 很火,火到了各行各业。记得去年更多的还是码农最新体验后拿它搜代码,现在各行各业都进来体验,问它咋理财、怎么写报告和给小孩起名。😂 也因此让小傅哥在头条的一篇关于 ChatGPT 的文章都有了26万...
小傅哥赞 6阅读 1.3k
程序员适合创业吗?
大家好,我是良许。从去年 12 月开始,我已经在视频号、抖音等主流视频平台上连续更新视频到现在,并得到了不错的评价。每个视频都花了很多时间精力用心制作,欢迎大家关注哦~考虑到有些小伙伴没有看过我的视频,...
良许赞 3阅读 1.3k
PyCharm 激活破解教程, 2023 年 2 月亲测有用
本文分享一下PyCharm 2022.2.3 版本最新激活破解教程,注意不要使用太新的版本,都是 Jetbrains 产品,本文专门配上了 Pycharm 的图片,跟着下面教程一步一步来即可。
程序员徐公阅读 9.8k评论 1
Ubuntu20.04 从源代码编译安装 python3.10
Ubuntu 22.04 Release DateUbuntu 22.04 Jammy Jellyfish is scheduled for release on April 21, 2022If you’re ready to use Ubuntu 22.04 Jammy Jellyfish, you can either upgrade your current Ubuntu syste...
ponponon赞 1阅读 4.6k评论 1
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。