摘要:在中,裝飾器一般用來(lái)修飾函數(shù),實(shí)現(xiàn)公共功能,達(dá)到代碼復(fù)用的目的。智能裝飾器上節(jié)介紹的寫法,嵌套層次較多,如果每個(gè)類似的裝飾器都用這種方法實(shí)現(xiàn),還是比較費(fèi)勁的腦子不夠用,也比較容易出錯(cuò)。假設(shè)有一個(gè)智能裝飾器,修飾裝飾器,便可獲得同樣的能力。
在Python中,裝飾器一般用來(lái)修飾函數(shù),實(shí)現(xiàn)公共功能,達(dá)到代碼復(fù)用的目的。在函數(shù)定義前加上@xxxx,然后函數(shù)就注入了某些行為,很神奇!然而,這只是語(yǔ)法糖而已。
原文地址:https://python-book.readthedocs.io場(chǎng)景
微信公眾號(hào):小菜學(xué)編程 (coding-fan)
假設(shè),有一些工作函數(shù),用來(lái)對(duì)數(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ù)包裝傻瓜解法無(wú)非是有太多代碼冗余,每次函數(shù)調(diào)用都要寫一遍logging??梢园堰@部分冗余邏輯封裝到一個(gè)新函數(shù)里:
def smart_work_bar(data): logging.info("begin call: work_bar") work_bar(data) logging.info("call done: work_bar")
這樣,每次調(diào)用smart_work_bar即可:
smart_work_bar(1) # ... smart_work_bar(some_data)通用閉包
看上去挺完美……然而,當(dāng)work_foo也有同樣的需要時(shí),還要再實(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
這個(gè)函數(shù)接收一個(gè)函數(shù)對(duì)象(被代理函數(shù))作為參數(shù),返回一個(gè)代理函數(shù)。調(diào)用代理函數(shù)時(shí),先輸出日志,然后調(diào)用被代理函數(shù),調(diào)用完成后再輸出日志,最后返回調(diào)用結(jié)果。這樣,不就達(dá)到通用化的目的了嗎?——對(duì)于任意被代理函數(shù)func,log_call均可輕松應(yīng)對(duì)。
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,返回一個(gè)代理函數(shù)proxy,并賦給smart_work_bar。第4行中,調(diào)用smart_work_bar,也就是代理函數(shù)proxy,先輸出日志,然后調(diào)用func也就是work_bar,最后再輸出日志。注意到,代理函數(shù)中,func與傳進(jìn)去的work_bar對(duì)象緊緊關(guān)聯(lián)在一起了,這就是閉包。
再提一下,可以覆蓋被代理函數(shù)名,以smart_為前綴取新名字還是顯得有些累贅:
work_bar = log_call(work_bar) work_foo = log_call(work_foo) work_bar(1) work_foo(1)語(yǔ)法糖
先來(lái)看看以下代碼:
def work_bar(data): pass work_bar = log_call(work_bar) def work_foo(data): pass work_foo = log_call(work_foo)
雖然代碼沒(méi)有什么冗余了,但是看是去還是不夠直觀。這時(shí)候,語(yǔ)法糖來(lái)了~~~
@log_call def work_bar(data): pass
因此,注意一點(diǎn)(劃重點(diǎn)啦),這里@log_call的作用只是:告訴Python編譯器插入代碼work_bar = log_call(work_bar)。
求值裝飾器先來(lái)猜猜裝飾器eval_now有什么作用?
def eval_now(func): return func()
看上去好奇怪哦,沒(méi)有定義代理函數(shù),算裝飾器嗎?
@eval_now def foo(): return 1 print foo
這段代碼輸出1,也就是對(duì)函數(shù)進(jìn)行調(diào)用求值。那么到底有什么用呢?直接寫foo = 1不行么?在這個(gè)簡(jiǎn)單的例子,這么寫當(dāng)然可以啦。來(lái)看一個(gè)更復(fù)雜的例子——初始化一個(gè)日志對(duì)象:
# 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)用在局部名字空間完成初始化,避免臨時(shí)變量(如formatter等)污染外部的名字空間(比如全局)。
帶參數(shù)裝飾器定義一個(gè)裝飾器,用于記錄慢函數(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)前時(shí)間,第7行計(jì)算調(diào)用耗時(shí),耗時(shí)大于一秒輸出一條警告日志。
@log_slow_call def sleep_seconds(seconds): time.sleep(seconds) sleep_seconds(0.1) # 沒(méi)有日志輸出 sleep_seconds(2) # 輸出警告日志
然而,閾值設(shè)置總是要視情況決定,不同的函數(shù)可能會(huì)設(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語(yǔ)法糖總是以被裝飾函數(shù)為參數(shù)調(diào)用裝飾器,也就是說(shuō)沒(méi)有機(jī)會(huì)傳遞threshold參數(shù)。怎么辦呢?——用一個(gè)閉包封裝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)
處女座可能會(huì)對(duì)第一行這對(duì)括號(hào)感到不爽,那么可以這樣改進(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)閾值(無(wú)調(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)。注意到,此時(shí)threshold關(guān)聯(lián)的值是0.5,完成定制化。
你可能注意到了,這里最好使用關(guān)鍵字參數(shù)這種調(diào)用方式——使用位置參數(shù)會(huì)很丑陋:
# 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é)介紹的寫法,嵌套層次較多,如果每個(gè)類似的裝飾器都用這種方法實(shí)現(xiàn),還是比較費(fèi)勁的(腦子不夠用),也比較容易出錯(cuò)。
假設(shè)有一個(gè)智能裝飾器smart_decorator,修飾裝飾器log_slow_call,便可獲得同樣的能力。這樣,log_slow_call定義將變得更清晰,實(shí)現(xiàn)起來(lái)也更省力啦:
@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
腦洞開(kāi)完,smart_decorator如何實(shí)現(xiàn)呢?其實(shí)也簡(jiǎn)單:
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è)想就成立了!這時(shí),log_slow_call,就是decorator_proxy(外層),關(guān)聯(lián)的閉包變量decorator是本節(jié)最開(kāi)始定義的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對(duì)象(內(nèi)層);再執(zhí)行decorator_proxy(sleep_seconds)(內(nèi)層);最后執(zhí)行decorator(func, **kwargs),等價(jià)于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對(duì)象(內(nèi)層);再執(zhí)行decorator_proxy(sleep_seconds)(內(nèi)層);最后執(zhí)行decorator(sleep_seconds, **kwargs),等價(jià)于real_log_slow_call(sleep_seconds, threshold=0.5),閾值實(shí)現(xiàn)自定義!
訂閱更新,獲取更多學(xué)習(xí)資料,請(qǐng)關(guān)注我們的?微信公眾號(hào)?:
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/43248.html
摘要:常規(guī)的使用來(lái)統(tǒng)計(jì)一段代碼運(yùn)行時(shí)間的例子輸出結(jié)果總結(jié)其實(shí)是一門特別人性化的語(yǔ)言,但凡在工程中經(jīng)常遇到的問(wèn)題,處理起來(lái)比較棘手的模式基本都有對(duì)應(yīng)的比較優(yōu)雅的解決方案。 python的高級(jí)特性 名詞與翻譯對(duì)照表 generator 生成器 iterator 迭代器 collection 集合 pack/unpack 打包/解包 decorator 裝飾器 context manager ...
摘要:裝飾器的高級(jí)用法介紹下面這些旨在介紹裝飾器的一些更有趣的用法。裝飾器在定義時(shí)向函數(shù)和方法添加功能,它們不用于在運(yùn)行時(shí)添加功能。接受參數(shù)的裝飾器有時(shí),除了裝飾的函數(shù)之外,裝飾器還可以使用參數(shù)。 showImg(https://segmentfault.com/img/remote/1460000019632097); 介紹 首先我要承認(rèn),裝飾器非常難!你在本教程中看到的一些代碼將會(huì)有一些...
摘要:為了避免重復(fù)調(diào)用,可以適當(dāng)?shù)刈鼍彺?,的裝飾器可以完美的完成這一任務(wù)。這意味著我們可以為方法創(chuàng)建裝飾器,只是要記得考慮。裝飾器封裝了函數(shù),這使得調(diào)試函數(shù)變得困難。另外,使用裝飾器去管理緩存和權(quán)限。 原文地址 之前用python簡(jiǎn)單寫了一下斐波那契數(shù)列的遞歸實(shí)現(xiàn)(如下),發(fā)現(xiàn)運(yùn)行速度很慢。 def fib_direct(n): assert n > 0, invalid n ...
摘要:今天我們一起探討一下裝飾器的另類用法。語(yǔ)法回顧開(kāi)始之前我們?cè)賹⒀b飾器的語(yǔ)法回顧一下。例子本身只是演示了裝飾器的一種用法,但不是推薦你就這樣使用裝飾器。類裝飾器在以前,還不支持類裝飾器。 之前有比較系統(tǒng)介紹過(guò)Python的裝飾器(請(qǐng)查閱《詳解Python裝飾器》),本文算是一個(gè)補(bǔ)充。今天我們一起探討一下裝飾器的另類用法。 語(yǔ)法回顧 開(kāi)始之前我們?cè)賹ython裝飾器的語(yǔ)法回顧一下。 @d...
摘要:接下來(lái)手工實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的裝飾器原型,緊接著引入中的裝飾器語(yǔ)法。最后還列出了一些裝飾器的高級(jí)用法,包括給裝飾器傳遞參數(shù)等。讀完整個(gè)答案,一定能對(duì)裝飾器有較深的理解,并且知道理解裝飾器的思考過(guò)程。 作為一名程序員,如果沒(méi)有聽(tīng)過(guò) Stackoverflow,那么你最好去面壁思過(guò)一下。程序員最需要閱讀的一本編程書(shū)籍(其實(shí)編程書(shū)留下這本就夠了?。?showImg(https://segmen...
閱讀 1707·2021-10-25 09:46
閱讀 3326·2021-10-08 10:04
閱讀 2442·2021-09-06 15:00
閱讀 2881·2021-08-19 10:57
閱讀 2144·2019-08-30 11:03
閱讀 1050·2019-08-30 11:00
閱讀 2495·2019-08-26 17:10
閱讀 3630·2019-08-26 13:36