0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

python 7個好用的裝飾器分享

python爬蟲知識分享 ? 來源:python爬蟲知識分享 ? 作者:python爬蟲知識分享 ? 2022-06-15 16:46 ? 次閱讀

1、dispach

Python 天然支持多態(tài),但使用 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 可以很方便地讓你實現(xiàn)命令行工具。

安裝:

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()

運行結(jié)果:

? 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

分布式的任務(wù)隊列,非 Celery 莫屬。

from celery import Celery

app = Celery('tasks', broker='pyamqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y

4、deprecated

這個相信大家在使用別的包時都遇到過,當(dāng)要下線一個老版本的函數(shù)的時候就可以使用這個裝飾器。

安裝:

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 程序中查找或創(chuàng)建兩個函數(shù)一樣簡單。我們可以用 @concurrent 裝飾需要并行運行的函數(shù),用 @synchronized 裝飾調(diào)用并行函數(shù)的函數(shù),使用舉例:

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

審核編輯:符乾江
聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 代碼
    +關(guān)注

    關(guān)注

    30

    文章

    4671

    瀏覽量

    67765
  • python
    +關(guān)注

    關(guān)注

    53

    文章

    4753

    瀏覽量

    84077
收藏 人收藏

    評論

    相關(guān)推薦

    python學(xué)習(xí):三測試庫的裝飾實現(xiàn)思路

    Python 中實現(xiàn)參數(shù)化測試的幾個庫,并留下一問題: 它們是如何做到把一方法變成多個方法,并且將每個方法與相應(yīng)的參數(shù)綁定起來的呢? 我們再提煉一下,原問題等于是:在一類中,
    的頭像 發(fā)表于 09-27 11:44 ?3031次閱讀
    <b class='flag-5'>python</b>學(xué)習(xí):三<b class='flag-5'>個</b>測試庫的<b class='flag-5'>裝飾</b><b class='flag-5'>器</b>實現(xiàn)思路

    理解Python裝飾及其工作原理

    Python 是一種對新手很友好的語言。但是,它也有很多較難掌握的高級功能,比如裝飾(decorator)。很多初學(xué)者一直不理解裝飾及其
    發(fā)表于 10-08 11:39 ?2162次閱讀

    好用python解釋

    解釋: CPython當(dāng)從Python官方網(wǎng)站下載并安裝好Python2.7后,就直接獲得了一官方版本的解釋:Cpython,這個解釋
    發(fā)表于 04-13 14:54

    分享python 7好用裝飾

    ): return x + y4、deprecated這個相信大家在使用別的包時都遇到過,當(dāng)要下線一老版本的函數(shù)的時候就可以使用這個裝飾。安裝:pip install Deprecated
    發(fā)表于 06-15 16:54

    一文讀懂Python裝飾

    裝飾前,還要先要明白一件事,Python 中的函數(shù)和 Java、C++不太一樣,Python 中的函數(shù)可以像普通變量一樣當(dāng)做參數(shù)傳遞給另外一
    發(fā)表于 04-28 10:48 ?3396次閱讀
    一文讀懂<b class='flag-5'>Python</b><b class='flag-5'>裝飾</b><b class='flag-5'>器</b>

    7Python調(diào)試通過的代碼詳細(xì)資料分析

    "Python的應(yīng)用十分廣泛,今天我們來分享7Python實戰(zhàn)項目代碼,希望你有所收獲。
    的頭像 發(fā)表于 10-14 09:46 ?3360次閱讀

    讓你學(xué)寫Python裝飾的五大理由

    你必須學(xué)寫Python裝飾的五理由
    的頭像 發(fā)表于 03-02 10:06 ?1818次閱讀

    Python的函數(shù)裝飾器使用方法

    Python中的裝飾是一種可以裝飾其它對象的工具,簡單地說,他們是修改其他函數(shù)的功能的函數(shù)。該工具本質(zhì)上是一可調(diào)用的對象(callabl
    的頭像 發(fā)表于 01-21 11:36 ?1513次閱讀
    <b class='flag-5'>Python</b>的函數(shù)<b class='flag-5'>裝飾</b>器使用方法

    Python裝飾的原理和案例

    Python中的裝飾器用于擴展可調(diào)用對象的功能,而無需修改其結(jié)構(gòu)?;旧?,裝飾函數(shù)包裝另一函數(shù)以增強或修改其行為。我們可以通過一
    的頭像 發(fā)表于 07-01 11:35 ?2154次閱讀

    Python裝飾的使用

    定義 首先我們先來了解下裝飾的定義。顧名思義,在Python中,裝飾本質(zhì)上就是一函數(shù),它可
    的頭像 發(fā)表于 06-21 16:54 ?664次閱讀

    8 好用的VS Code Python 擴展

    今天為大家分享 8 好用的 VS Code Python 擴展。 1. Python extension for Visual Studio Code 這個擴展是由微軟官方提供的,支
    的頭像 發(fā)表于 10-16 11:11 ?702次閱讀
    8 <b class='flag-5'>個</b><b class='flag-5'>好用</b>的VS Code <b class='flag-5'>Python</b> 擴展

    Python自制簡單實用的日志裝飾

    在寫代碼的時候,往往會漏掉日志這個關(guān)鍵因素,導(dǎo)致功能在使用的時候出錯卻無法溯源。 其實,只需要寫一非常簡單的日志裝飾,我們就能大大提升排查問題的效率。 1.簡陋版裝飾
    的頭像 發(fā)表于 10-21 14:39 ?614次閱讀
    <b class='flag-5'>Python</b>自制簡單實用的日志<b class='flag-5'>裝飾</b><b class='flag-5'>器</b>

    Python 自制簡單實用的日志裝飾

    在寫代碼的時候,往往會漏掉日志這個關(guān)鍵因素,導(dǎo)致功能在使用的時候出錯卻無法溯源。 其實,只需要寫一非常簡單的日志裝飾,我們就能大大提升排查問題的效率。 1.簡陋版裝飾
    的頭像 發(fā)表于 10-31 15:05 ?429次閱讀
    <b class='flag-5'>Python</b> 自制簡單實用的日志<b class='flag-5'>裝飾</b><b class='flag-5'>器</b>

    如何寫一簡單的裝飾

    今天介紹的是一已經(jīng)存在十三年,但是依舊不紅的庫 decorator,好像很少有人知道他的存在一樣。 這個庫可以幫你做什么呢 ? 其實很簡單,就是可以幫你更方便地寫python裝飾
    的頭像 發(fā)表于 11-01 09:54 ?402次閱讀
    如何寫一<b class='flag-5'>個</b>簡單的<b class='flag-5'>裝飾</b><b class='flag-5'>器</b>

    【每天學(xué)點AI】一例子帶你了解Python裝飾到底在干嘛!

    進行“加料”呢?Python裝飾提供了一更為優(yōu)雅的方式來增強現(xiàn)有函數(shù)的行為,并且不需要修改現(xiàn)有的函數(shù)代碼及調(diào)用方式。接下來通過一案例來
    的頭像 發(fā)表于 09-20 16:54 ?183次閱讀
    【每天學(xué)點AI】一<b class='flag-5'>個</b>例子帶你了解<b class='flag-5'>Python</b><b class='flag-5'>裝飾</b><b class='flag-5'>器</b>到底在干嘛!