實例講解Python的函數(shù)閉包使用中應注意的問題
昨天正當我用十成一陽指功力戳鍵盤、昏天暗地coding的時候,正好被人問了一個問題,差點沒收好功,洪荒之力側(cè)漏震傷桌邊的人,廢話不多說,先上栗子(精簡版,只為說明問題):
from functools import wraps from time import sleep def retry(attempts=3, wait=2): if attempts < 0 or attempts > 5: retry_times = 3 else: retry_times = attempts if wait < 0 or wait > 5: retry_wait = 2 else: retry_wait = after def retry_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): while retry_times > 0: try: return func(*args, **kwargs) except : sleep(retry_wait) retry_times -= 1 return wrapped_function return retry_decorator
簡易版的retry裝飾器,需要的變量被閉包完美捕捉,邏輯也挺簡單明了。問的人說邏輯看著挺正常的,但就是一直報變量retry_times找不到(unresolved reference)的錯誤提示。
沒錯仔細捋一下,這是一道送分題呢:閉包捕獲的變量(retry_times,retry_wait)相當時引用的retry函數(shù)的局部變量,當在wrapped_function的局部作用于里面操作不可變類型的數(shù)據(jù)時,會生成新的局部變量,但是新生成的局部變量retry_times在使用時還沒來得及初始化,因此會提示找不到變量;retry_wait相反能被好好的使用到。
python是duck-typing的編程語言,就算有warning照樣跑,寫個簡單到極限的的函數(shù),用一下裝飾器,在wrapped_function邏輯里打個斷點看一下各個變量的值也是很快能找到問題的(直接跑也能看到錯誤:UnboundLocalError: local variable 'retry_attempts' referenced before assignment, 至少比warning msg有用):
@retry(7, 8) def test(): print 23333 raise Exception('Call me exception 2333.') if __name__ == '__main__': test() output: UnboundLocalError: local variable 'retry_times' referenced before assignment
要解決這種問題也好辦,用一個可變的容器把要用的不可變類型的數(shù)據(jù)包裝一下就行了(說個好久沒寫C#代碼記不太清楚完全不負責任的題外話,就像在C#.net里面,碰到閉包的時候,會自動生成一個混淆過名字的類然后把要被捕捉的值當作類的屬性存著,這樣在使用的時候就能輕松get,著名的老趙好像有一篇文章講Lazy Evaluation的好像涉及到這個話題):
def retry(attempts=3, wait=2): temp_dict = { 'retry_times': 3 if attempts < 0 or attempts > 5 else attempts, 'retry_wait': 2 if wait < 0 or wait > 5 else wait } def retry_decorate(fn): @wraps(fn) def wrapped_function(*args, **kwargs): print id(temp_dict), temp_dict while temp_dict.get('retry_times') > 0: try: return fn(*args, **kwargs) except : sleep(temp_dict.get('retry_wait')) temp_dict['retry_times'] = temp_dict.get('retry_times') - 1 print id(temp_dict), temp_dict print id(temp_dict), temp_dict return wrapped_function return retry_decorate @retry(7, 8) def test(): print 23333 raise Exception('Call me exception 2333.') if __name__ == '__main__': test()
輸出:
4405472064 {'retry_wait': 2, 'retry_times': 3} 4405472064 {'retry_wait': 2, 'retry_times': 3} 23333 4405472064 {'retry_wait': 2, 'retry_times': 2} 23333 4405472064 {'retry_wait': 2, 'retry_times': 1} 23333 4405472064 {'retry_wait': 2, 'retry_times': 0}
從output中可以看到,用dict包裝后,程序能夠正常的工作,和預期的一致,其實我們也可以從函數(shù)的閉包的值再次確認:
>>> test.func_closure[1].cell_contents {'retry_wait': 2, 'retry_times': 2}
我是結(jié)尾,PEACE!
相關文章
python issubclass 和 isinstance函數(shù)
這篇文章主要介紹了python issubclass 和 isinstance函數(shù),本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07Python常用內(nèi)建模塊hashlib、hmac詳解
這篇文章主要介紹了Python常用內(nèi)建模塊hashlib、hmac詳解,摘要算法又稱哈希算法、散列算法,它通過一個函數(shù),把任意長度的數(shù)據(jù)轉(zhuǎn)換為一個長度固定的數(shù)據(jù)串,需要的朋友可以參考下2023-08-08Python列表排序 list.sort方法和內(nèi)置函數(shù)sorted用法
這篇文章主要介紹了Python列表排序 list.sort方法和內(nèi)置函數(shù)sorted用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python爬蟲模擬登陸嗶哩嗶哩(bilibili)并突破點選驗證碼功能
這篇文章主要介紹了Python爬蟲模擬登陸嗶哩嗶哩(bilibili)并突破點選驗證碼功能,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Pytorch中實現(xiàn)只導入部分模型參數(shù)的方式
今天小編就為大家分享一篇Pytorch中實現(xiàn)只導入部分模型參數(shù)的方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Pandas數(shù)值排序 sort_values()的使用
本文主要介紹了Pandas數(shù)值排序 sort_values()的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07Python實現(xiàn)簡單圖像縮放與旋轉(zhuǎn)
大家好,本篇文章主要講的是Python實現(xiàn)簡單圖像縮放與旋轉(zhuǎn),感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01