python 7个好用的装饰器分享

python爬虫知识分享 来源:python爬虫知识分享 作者:python爬虫知识分享 2022-06-15 16:46 次阅读

1、dispach

Python 天然支持多态,但使用 dispatch 可以让你的代码更加容易阅读。

安装:

pipinstallmultipledispatch

使用:

>>> 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 可以很方便地让你实现命令行工具。

安装:

pipinstallclick

使用: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

这个相信大家在使用别的包时都遇到过,当要下线一个老版本的函数的时候就可以使用这个装饰器。

安装:

pipinstallDeprecated

使用: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

安装:

pipinstalldeco

使用 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

缓存工具

安装:

pipinstallcachetools

使用:

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

重试装饰器,支持各种各样的重试需求。

安装:

pipinstalltenacity

使用:

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

审核编辑:符乾江
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 代码
    +关注

    关注

    30

    文章

    4554

    浏览量

    66734
  • python
    +关注

    关注

    51

    文章

    4671

    浏览量

    83458
收藏 人收藏

    评论

    相关推荐

    python学习:三个测试库的装饰器实现思路

    Python 中实现参数化测试的几个库,并留下一个问题: 它们是如何做到把一个方法变成多个方法,并且将每个方法与相应的参数绑定起来的呢? 我们再提炼一下,原问题等于是:在一个类中,如何使用装饰
    的头像 发表于 09-27 11:44 2857次阅读
    <b class='flag-5'>python</b>学习:三个测试库的<b class='flag-5'>装饰</b>器实现思路

    理解Python装饰器及其工作原理

    Python 是一种对新手很友好的语言。但是,它也有很多较难掌握的高级功能,比如装饰器(decorator)。很多初学者一直不理解装饰器及其工作原理,在这篇文章中,我们将介绍装饰器的来
    发表于 10-08 11:39 2067次阅读

    Python哪个版本好用

    想学习Python的人都会有一困惑,那就是Python目前有两版本Python2和Python
    发表于 01-26 16:39

    好用python解释

    解释: CPython当从Python官方网站下载并安装好Python2.7后,就直接获得了一官方版本的解释:Cpython,这个解释
    发表于 04-13 14:54

    如何利用Python去实现一带有计时功能的装饰

    ,functools.lrucache()是非常实用的装饰,它实现了备忘(memoization)功能。这是一项优化技术,它把耗时的函数的结果保存起来,避免传入相同的参数时重复计算。LRU三字母是“Least
    发表于 03-23 11:07

    分享python 7好用装饰

    ): return x + y4、deprecated这个相信大家在使用别的包时都遇到过,当要下线一老版本的函数的时候就可以使用这个装饰。安装:pip install Deprecated
    发表于 06-15 16:54

    一文读懂Python装饰

    装饰器前,还要先要明白一件事,Python 中的函数和 Java、C++不太一样,Python 中的函数可以像普通变量一样当做参数传递给另外一个函数。
    发表于 04-28 10:48 3335次阅读
    一文读懂<b class='flag-5'>Python</b><b class='flag-5'>装饰</b>器

    这些非常好用的的Python库你知道多少

    下面给大家推荐几个我用过的,并且特别好用的项目,而不是简单的贴一下awesome python。相信很多人看完awesome python以后,只是简单的收藏一下,并没有很多帮助。
    的头像 发表于 12-31 14:41 2999次阅读
    这些非常<b class='flag-5'>好用</b>的的<b class='flag-5'>Python</b>库你知道多少

    让你学写Python装饰器的五大理由

    你必须学写Python装饰器的五个理由
    的头像 发表于 03-02 10:06 1708次阅读

    Python的函数装饰器使用方法

    Python中的装饰器是一种可以装饰其它对象的工具,简单地说,他们是修改其他函数的功能的函数。该工具本质上是一个可调用的对象(callable),所以装饰器一般可以由函数、类来实现;
    的头像 发表于 01-21 11:36 1406次阅读
    <b class='flag-5'>Python</b>的函数<b class='flag-5'>装饰</b>器使用方法

    Python装饰器的原理和案例

    Python中的装饰器用于扩展可调用对象的功能,而无需修改其结构。基本上,装饰器函数包装另一个函数以增强或修改其行为。我们可以通过一个具体的例子了解基础知识!让我们编写一个包含装饰器实
    的头像 发表于 07-01 11:35 2012次阅读

    Python装饰器的使用

    定义 首先我们先来了解下装饰器的定义。顾名思义,在Python中,装饰器本质上就是一个函数,它可以接收一个函数作为参数,然后返回一个新的函数。这个新的函数可以在执行原有函数之前或之后,对函数进行一些
    的头像 发表于 06-21 16:54 553次阅读

    Python自制简单实用的日志装饰

    在写代码的时候,往往会漏掉日志这个关键因素,导致功能在使用的时候出错却无法溯源。 其实,只需要写一个非常简单的日志装饰器,我们就能大大提升排查问题的效率。 1.简陋版装饰器 写一个装饰器非常简单
    的头像 发表于 10-21 14:39 313次阅读
    <b class='flag-5'>Python</b>自制简单实用的日志<b class='flag-5'>装饰</b>器

    Python 自制简单实用的日志装饰

    在写代码的时候,往往会漏掉日志这个关键因素,导致功能在使用的时候出错却无法溯源。 其实,只需要写一个非常简单的日志装饰器,我们就能大大提升排查问题的效率。 1.简陋版装饰器 写一个装饰器非常简单
    的头像 发表于 10-31 15:05 306次阅读
    <b class='flag-5'>Python</b> 自制简单实用的日志<b class='flag-5'>装饰</b>器

    如何写一个简单的装饰

    今天介绍的是一个已经存在十三年,但是依旧不红的库 decorator,好像很少有人知道他的存在一样。 这个库可以帮你做什么呢 ? 其实很简单,就是可以帮你更方便地写python装饰器代码,更重
    的头像 发表于 11-01 09:54 268次阅读
    如何写一个简单的<b class='flag-5'>装饰</b>器