Python七个好用的装饰器

更新日期: 2022-06-15阅读: 1.4k标签: Python

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

链接: https://www.fly63.com/article/detial/11745

9 个用于前端开发的Python 框架:JavaScript 替代品

JavaScript 是 Web 开发领域里非常重要的技术之一,并且是每个开发者都必须掌握的技能。而我作为一个开始使用 Python 编程的人

30个非常实用的Python技巧

Python 是机器学习最广泛采用的编程语言,它最重要的优势在于编程的易用性。如果读者对基本的 Python 语法已经有一些了解,那么这篇文章可能会给你一些启发。作者简单概览了 30 段代码,它们都是平常非常实用的技巧

25个超有用的Python代码段

Python是一种通用的高级编程语言。用它可以做许多事,比如开发桌面 GUI 应用程序、网站和 Web 应用程序等。作为一种高级编程语言,Python 还可以让你通过处理常见的编程任务来专注应用程序的核心功能。

如何选择异步Web Python框架

Python在3.4引入了 asyncio 库,3.6新增了关键字 async 和 await ,此后,异步框架迅速发展了起来,性能上能和Node.js比肩,除非是CPU密集型任务,否则没有理由不适用异步框架

11 个优秀的 Python 编译器和解释器

Python 是一门对初学者友好的编程语言,是一种多用途的、解释性的和面向对象的高级语言。它拥有非常小的程序集,非常易于学习、阅读和维护。其解释器可在Windows、Linux 和 Mac OS 等多种操作系统上使用

写 Python 代码不可不知的函数式编程技术

在 Python 中,函数是「头等公民」(first-class)。也就是说,函数与其他数据类型(如 int)处于平等地位。因而,我们可以将函数赋值给变量,也可以将其作为参数传入其他函数

Python 中 3 个不可思议的返回

Python 字典通过检查键值是否相等和比较哈希值来确定两个键是否相同.具有相同值的不可变对象在Python中始终具有相同的哈希值.注意: 具有不同值的对象也可能具有相同的哈希值(哈希冲突)

Python 实现单例模式

而且上面这种方法只有第一次 get_instance() 的时候能给对象传递参数,总之有许多弊端。Python 提供了 __new__ 方法正好完美解决了这个问题,再加上锁,就能实现一个线程安全的单例模式:

常见Python的Web开发框架

web开发框架存在的意义就在于可以快速便捷的构建应用,而不用去在意那些没必要的技术细节,到2020年为止,基于Python创建的的web应用已经非常多了,国外知名的有youtube.com、instagram、reditt、国内有知乎、豆瓣等等

nodejs中怎么调用python函数?

每种语言都有自己的优势,互相结合起来各取所长程序执行起来效率更高或者说哪种实现方式较简单就用哪个,nodejs是利用子进程来调用系统命令或者文件,NodeJS子进程提供了与系统交互的重要接口,其主要API有: 标准输入

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!