关于python:七个好用的装饰器

4次阅读

共计 3349 个字符,预计需要花费 9 分钟才能阅读完成。

分享七个好用的装璜器,不便你撸代码。

 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”还可支付大量学习材料。或是返回编程学习网,理解更多编程技术常识。

正文完
 0