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

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

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

python 7個(gè)好用的裝飾器分享

python爬蟲(chóng)知識(shí)分享 ? 來(lái)源:python爬蟲(chóng)知識(shí)分享 ? 作者:python爬蟲(chóng)知識(shí)分享 ? 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 可以很方便地讓你實(shí)現(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()

運(yùn)行結(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ù)隊(duì)列,非 Celery 莫屬。

from celery import Celery

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

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

4、deprecated

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

安裝:

pipinstallDeprecated

使用:demo4.py

from deprecated import deprecated
@deprecated ("This function is deprecated, please do not use it")
def func1():
    pass

func1()

運(yùn)行效果如下:

? 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)建兩個(gè)函數(shù)一樣簡(jiǎn)單。我們可以用 @concurrent 裝飾需要并行運(yùn)行的函數(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)容及配圖由入駐作者撰寫(xiě)或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問(wèn)題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • 代碼
    +關(guān)注

    關(guān)注

    30

    文章

    4695

    瀏覽量

    68080
  • python
    +關(guān)注

    關(guān)注

    54

    文章

    4758

    瀏覽量

    84287
收藏 人收藏

    評(píng)論

    相關(guān)推薦

    python學(xué)習(xí):三個(gè)測(cè)試庫(kù)的裝飾實(shí)現(xiàn)思路

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

    理解Python裝飾及其工作原理

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

    好用python解釋

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

    分享python 7個(gè)好用裝飾

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

    一文讀懂Python裝飾

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

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

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

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

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

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

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

    Python裝飾的原理和案例

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

    Python裝飾的使用

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

    8 個(gè)好用的VS Code Python 擴(kuò)展

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

    Python自制簡(jiǎn)單實(shí)用的日志裝飾

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

    Python 自制簡(jiǎn)單實(shí)用的日志裝飾

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

    如何寫(xiě)一個(gè)簡(jiǎn)單的裝飾

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

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

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