欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中裝飾器高級用法詳解

 更新時間:2017年12月25日 08:45:59   作者:fasionchan  
這篇文章主要介紹了Python中的裝飾器的高級用法,以實(shí)例形式詳細(xì)的分析了Python中的裝飾器的使用技巧及相關(guān)注意事項(xiàng)

在Python中,裝飾器一般用來修飾函數(shù),實(shí)現(xiàn)公共功能,達(dá)到代碼復(fù)用的目的。在函數(shù)定義前加上@xxxx,然后函數(shù)就注入了某些行為,很神奇!然而,這只是語法糖而已。

場景

假設(shè),有一些工作函數(shù),用來對數(shù)據(jù)做不同的處理:

def work_bar(data):
  pass

def work_foo(data):
  pass

我們想在函數(shù)調(diào)用前/后輸出日志,怎么辦?

傻瓜解法

logging.info('begin call work_bar')
work_bar(1)
logging.info('call work_bar done')

如果有多處代碼調(diào)用呢?想想就怕!

函數(shù)包裝

傻瓜解法無非是有太多代碼冗余,每次函數(shù)調(diào)用都要寫一遍logging??梢园堰@部分冗余邏輯封裝到一個新函數(shù)里:

def smart_work_bar(data):
  logging.info('begin call: work_bar')
  work_bar(data)
  logging.info('call doen: work_bar')

這樣,每次調(diào)用smart_work_bar即可:

smart_work_bar(1)

# ...

smart_work_bar(some_data)

通用閉包

看上去挺完美……然而,當(dāng)work_foo也有同樣的需要時,還要再實(shí)現(xiàn)一遍smart_work_foo嗎?這樣顯然不科學(xué)呀!

別急,我們可以用閉包:

def log_call(func):
  def proxy(*args, **kwargs):
    logging.info('begin call: {name}'.format(name=func.func_name))
    result = func(*args, **kwargs)
    logging.info('call done: {name}'.format(name=func.func_name))
    return result
  return proxy

這個函數(shù)接收一個函數(shù)對象(被代理函數(shù))作為參數(shù),返回一個代理函數(shù)。調(diào)用代理函數(shù)時,先輸出日志,然后調(diào)用被代理函數(shù),調(diào)用完成后再輸出日志,最后返回調(diào)用結(jié)果。這樣,不就達(dá)到通用化的目的了嗎?——對于任意被代理函數(shù)func,log_call均可輕松應(yīng)對。

smart_work_bar = log_call(work_bar)
smart_work_foo = log_call(work_foo)

smart_work_bar(1)
smart_work_foo(1)

# ...

smart_work_bar(some_data)
smart_work_foo(some_data)

第1行中,log_call接收參數(shù)work_bar,返回一個代理函數(shù)proxy,并賦給smart_work_bar。第4行中,調(diào)用smart_work_bar,也就是代理函數(shù)proxy,先輸出日志,然后調(diào)用func也就是work_bar,最后再輸出日志。注意到,代理函數(shù)中,func與傳進(jìn)去的work_bar對象緊緊關(guān)聯(lián)在一起了,這就是閉包。

再提一下,可以覆蓋被代理函數(shù)名,以smart_為前綴取新名字還是顯得有些累贅:

work_bar = log_call(work_bar)
work_foo = log_call(work_foo)

work_bar(1)
work_foo(1)

語法糖

先來看看以下代碼:

def work_bar(data):
  pass
work_bar = log_call(work_bar)


def work_foo(data):
  pass
work_foo = log_call(work_foo)

雖然代碼沒有什么冗余了,但是看是去還是不夠直觀。這時候,語法糖來了~~~

@log_call
def work_bar(data):
  pass

因此,注意一點(diǎn)(劃重點(diǎn)啦),這里@log_call的作用只是:告訴Python編譯器插入代碼work_bar = log_call(work_bar)。

求值裝飾器

先來猜猜裝飾器eval_now有什么作用?

def eval_now(func):
  return func()

看上去好奇怪哦,沒有定義代理函數(shù),算裝飾器嗎?

@eval_now
def foo():
  return 1

print foo

這段代碼輸出1,也就是對函數(shù)進(jìn)行調(diào)用求值。那么到底有什么用呢?直接寫foo = 1不行么?在這個簡單的例子,這么寫當(dāng)然可以啦。來看一個更復(fù)雜的例子——初始化一個日志對象:

# some other code before...

# log format
formatter = logging.Formatter(
  '[%(asctime)s] %(process)5d %(levelname) 8s - %(message)s',
  '%Y-%m-%d %H:%M:%S',
)

# stdout handler
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
stdout_handler.setLevel(logging.DEBUG)

# stderr handler
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setFormatter(formatter)
stderr_handler.setLevel(logging.ERROR)

# logger object
logger = logging.Logger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(stdout_handler)
logger.addHandler(stderr_handler)

# again some other code after...

用eval_now的方式:

# some other code before...

@eval_now
def logger():
  # log format
  formatter = logging.Formatter(
    '[%(asctime)s] %(process)5d %(levelname) 8s - %(message)s',
    '%Y-%m-%d %H:%M:%S',
  )

  # stdout handler
  stdout_handler = logging.StreamHandler(sys.stdout)
  stdout_handler.setFormatter(formatter)
  stdout_handler.setLevel(logging.DEBUG)

  # stderr handler
  stderr_handler = logging.StreamHandler(sys.stderr)
  stderr_handler.setFormatter(formatter)
  stderr_handler.setLevel(logging.ERROR)

  # logger object
  logger = logging.Logger(__name__)
  logger.setLevel(logging.DEBUG)
  logger.addHandler(stdout_handler)
  logger.addHandler(stderr_handler)

  return logger

# again some other code after...

兩段代碼要達(dá)到的目的是一樣的,但是后者顯然更清晰,頗有代碼塊的風(fēng)范。更重要的是,函數(shù)調(diào)用在局部名字空間完成初始化,避免臨時變量(如formatter等)污染外部的名字空間(比如全局)。

帶參數(shù)裝飾器

定義一個裝飾器,用于記錄慢函數(shù)調(diào)用:

def log_slow_call(func):
  def proxy(*args, **kwargs):
    start_ts = time.time()
    result = func(*args, **kwargs)
    end_ts = time.time()

    seconds = start_ts - end_ts
    if seconds > 1:
    logging.warn('slow call: {name} in {seconds}s'.format(
      name=func.func_name,
      seconds=seconds,
    ))

    return result

  return proxy

第3、5行分別在函數(shù)調(diào)用前后采樣當(dāng)前時間,第7行計算調(diào)用耗時,耗時大于一秒輸出一條警告日志。

@log_slow_call
def sleep_seconds(seconds):
  time.sleep(seconds)

sleep_seconds(0.1) # 沒有日志輸出

sleep_seconds(2)  # 輸出警告日志

然而,閾值設(shè)置總是要視情況決定,不同的函數(shù)可能會設(shè)置不同的值。如果閾值有辦法參數(shù)化就好了:

def log_slow_call(func, threshold=1):
  def proxy(*args, **kwargs):
    start_ts = time.time()
    result = func(*args, **kwargs)
    end_ts = time.time()

    seconds = start_ts - end_ts
    if seconds > threshold:
    logging.warn('slow call: {name} in {seconds}s'.format(
      name=func.func_name,
      seconds=seconds,
    ))

    return result

  return proxy

然而,@xxxx語法糖總是以被裝飾函數(shù)為參數(shù)調(diào)用裝飾器,也就是說沒有機(jī)會傳遞threshold參數(shù)。怎么辦呢?——用一個閉包封裝threshold參數(shù):

def log_slow_call(threshold=1):
  def decorator(func):
    def proxy(*args, **kwargs):
      start_ts = time.time()
      result = func(*args, **kwargs)
      end_ts = time.time()

      seconds = start_ts - end_ts
      if seconds > threshold:
      logging.warn('slow call: {name} in {seconds}s'.format(
        name=func.func_name,
        seconds=seconds,
      ))

      return result

    return proxy

  return decorator


@log_slow_call(threshold=0.5)
def sleep_seconds(seconds):
  time.sleep(seconds)

這樣,log_slow_call(threshold=0.5)調(diào)用返回函數(shù)decorator,函數(shù)擁有閉包變量threshold,值為0.5。decorator再裝飾sleep_seconds。

采用默認(rèn)閾值,函數(shù)調(diào)用還是不能省略:

@log_slow_call()
def sleep_seconds(seconds):
  time.sleep(seconds)

處女座可能會對第一行這對括號感到不爽,那么可以這樣改進(jìn):

def log_slow_call(func=None, threshold=1):
  def decorator(func):
    def proxy(*args, **kwargs):
      start_ts = time.time()
      result = func(*args, **kwargs)
      end_ts = time.time()

      seconds = start_ts - end_ts
      if seconds > threshold:
      logging.warn('slow call: {name} in {seconds}s'.format(
        name=func.func_name,
        seconds=seconds,
      ))

      return result

    return proxy

  if func is None:
    return decorator
  else:
    return decorator(func)

這種寫法兼容兩種不同的用法,用法A默認(rèn)閾值(無調(diào)用);用法B自定義閾值(有調(diào)用)。

# Case A
@log_slow_call
def sleep_seconds(seconds):
  time.sleep(seconds)


# Case B
@log_slow_call(threshold=0.5)
def sleep_seconds(seconds):
  time.sleep(seconds)

用法A中,發(fā)生的事情是log_slow_call(sleep_seconds),也就是func參數(shù)是非空的,這是直接調(diào)decorator進(jìn)行包裝并返回(閾值是默認(rèn)的)。

用法B中,先發(fā)生的是log_slow_call(threshold=0.5),func參數(shù)為空,直接返回新的裝飾器decorator,關(guān)聯(lián)閉包變量threshold,值為0.5;然后,decorator再裝飾函數(shù)sleep_seconds,即decorator(sleep_seconds)。注意到,此時threshold關(guān)聯(lián)的值是0.5,完成定制化。

你可能注意到了,這里最好使用關(guān)鍵字參數(shù)這種調(diào)用方式——使用位置參數(shù)會很丑陋:

# Case B-
@log_slow_call(None, 0.5)
def sleep_seconds(seconds):
  time.sleep(seconds)

當(dāng)然了,函數(shù)調(diào)用盡量使用關(guān)鍵字參數(shù)是一種極佳實(shí)踐,含義清晰,在參數(shù)很多的情況下更是如此。

智能裝飾器

上節(jié)介紹的寫法,嵌套層次較多,如果每個類似的裝飾器都用這種方法實(shí)現(xiàn),還是比較費(fèi)勁的(腦子不夠用),也比較容易出錯。

假設(shè)有一個智能裝飾器smart_decorator,修飾裝飾器log_slow_call,便可獲得同樣的能力。這樣,log_slow_call定義將變得更清晰,實(shí)現(xiàn)起來也更省力啦:

@smart_decorator
def log_slow_call(func, threshold=1):
  def proxy(*args, **kwargs):
    start_ts = time.time()
    result = func(*args, **kwargs)
    end_ts = time.time()

    seconds = start_ts - end_ts
    if seconds > threshold:
    logging.warn('slow call: {name} in {seconds}s'.format(
      name=func.func_name,
      seconds=seconds,
    ))

    return result

  return proxy

腦洞開完,smart_decorator如何實(shí)現(xiàn)呢?其實(shí)也簡單:

def smart_decorator(decorator):

  def decorator_proxy(func=None, **kwargs):
    if func is not None:
      return decorator(func=func, **kwargs)

    def decorator_proxy(func):
      return decorator(func=func, **kwargs)

    return decorator_proxy

  return decorator_proxy

smart_decorator實(shí)現(xiàn)了以后,設(shè)想就成立了!這時,log_slow_call,就是decorator_proxy(外層),關(guān)聯(lián)的閉包變量decorator是本節(jié)最開始定義的log_slow_call(為了避免歧義,稱為real_log_slow_call)。log_slow_call支持以下各種用法:

# Case A
@log_slow_call
def sleep_seconds(seconds):
  time.sleep(seconds)

用法A中,執(zhí)行的是decorator_proxy(sleep_seconds)(外層),func非空,kwargs為空;直接執(zhí)行decorator(func=func, **kwargs),即real_log_slow_call(sleep_seconds),結(jié)果是關(guān)聯(lián)默認(rèn)參數(shù)的proxy。

# Case B
# Same to Case A
@log_slow_call()
def sleep_seconds(seconds):
  time.sleep(seconds)

用法B中,先執(zhí)行decorator_proxy(),func及kwargs均為空,返回decorator_proxy對象(內(nèi)層);再執(zhí)行decorator_proxy(sleep_seconds)(內(nèi)層);最后執(zhí)行decorator(func, **kwargs),等價于real_log_slow_call(sleep_seconds),效果與用法A一致。

# Case C
@log_slow_call(threshold=0.5)
def sleep_seconds(seconds):
  time.sleep(seconds)

用法C中,先執(zhí)行decorator_proxy(threshold=0.5),func為空但kwargs非空,返回decorator_proxy對象(內(nèi)層);再執(zhí)行decorator_proxy(sleep_seconds)(內(nèi)層);最后執(zhí)行decorator(sleep_seconds, **kwargs),等價于real_log_slow_call(sleep_seconds, threshold=0.5),閾值實(shí)現(xiàn)自定義!

相關(guān)文章

  • Python使用imagehash庫生成ahash算法的示例代碼

    Python使用imagehash庫生成ahash算法的示例代碼

    aHash、pHash、dHash是常用的圖像相似度識別算法,本文將利用Python中的imagehash庫生成這一算法,從而實(shí)現(xiàn)計算圖片相似度,感興趣的可以了解一下
    2022-11-11
  • Python實(shí)現(xiàn)文件只讀屬性的設(shè)置與取消

    Python實(shí)現(xiàn)文件只讀屬性的設(shè)置與取消

    這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)設(shè)置文件只讀與取消文件只讀的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下
    2023-07-07
  • python關(guān)于第三方日志的QA記錄詳解

    python關(guān)于第三方日志的QA記錄詳解

    這篇文章主要為大家介紹了python關(guān)于第三方日志的QA記錄詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10
  • 在Pycharm中安裝Pandas庫方法(簡單易懂)

    在Pycharm中安裝Pandas庫方法(簡單易懂)

    這篇文章主要介紹了在Pycharm中安裝Pandas庫方法,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Python實(shí)現(xiàn)從url中提取域名的幾種方法

    Python實(shí)現(xiàn)從url中提取域名的幾種方法

    這篇文章主要介紹了Python實(shí)現(xiàn)從url中提取域名的幾種方法,本文給出了3種方法實(shí)現(xiàn)在URL中提取域名的需求,需要的朋友可以參考下
    2014-09-09
  • Python queue模塊攻略全解

    Python queue模塊攻略全解

    這篇文章主要為大家介紹了Python queue模塊攻略全解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • python開發(fā)之a(chǎn)naconda以及win7下安裝gensim的方法

    python開發(fā)之a(chǎn)naconda以及win7下安裝gensim的方法

    這篇文章主要介紹了python開發(fā)之a(chǎn)naconda以及win7下安裝gensim的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • 如何打包Python Web項(xiàng)目實(shí)現(xiàn)免安裝一鍵啟動的方法

    如何打包Python Web項(xiàng)目實(shí)現(xiàn)免安裝一鍵啟動的方法

    這篇文章主要介紹了如何打包Python Web項(xiàng)目,實(shí)現(xiàn)免安裝一鍵啟動,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-05-05
  • Python pyinstaller庫的安裝配置教程分享

    Python pyinstaller庫的安裝配置教程分享

    pyinstaller模塊主要用于python代碼打包成exe程序直接使用,這樣在其它電腦上即使沒有python環(huán)境也是可以運(yùn)行的。本文就來和大家分享一下pyinstaller庫的安裝配置教程,希望對大家有所幫助
    2023-04-04
  • python裝飾器使用實(shí)例詳解

    python裝飾器使用實(shí)例詳解

    這篇文章主要介紹了python裝飾器使用實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12

最新評論