實(shí)例講解Python的函數(shù)閉包使用中應(yīng)注意的問(wèn)題
昨天正當(dāng)我用十成一陽(yáng)指功力戳鍵盤、昏天暗地coding的時(shí)候,正好被人問(wèn)了一個(gè)問(wèn)題,差點(diǎn)沒(méi)收好功,洪荒之力側(cè)漏震傷桌邊的人,廢話不多說(shuō),先上栗子(精簡(jiǎn)版,只為說(shuō)明問(wèn)題):
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
簡(jiǎn)易版的retry裝飾器,需要的變量被閉包完美捕捉,邏輯也挺簡(jiǎn)單明了。問(wèn)的人說(shuō)邏輯看著挺正常的,但就是一直報(bào)變量retry_times找不到(unresolved reference)的錯(cuò)誤提示。
沒(méi)錯(cuò)仔細(xì)捋一下,這是一道送分題呢:閉包捕獲的變量(retry_times,retry_wait)相當(dāng)時(shí)引用的retry函數(shù)的局部變量,當(dāng)在wrapped_function的局部作用于里面操作不可變類型的數(shù)據(jù)時(shí),會(huì)生成新的局部變量,但是新生成的局部變量retry_times在使用時(shí)還沒(méi)來(lái)得及初始化,因此會(huì)提示找不到變量;retry_wait相反能被好好的使用到。
python是duck-typing的編程語(yǔ)言,就算有warning照樣跑,寫個(gè)簡(jiǎn)單到極限的的函數(shù),用一下裝飾器,在wrapped_function邏輯里打個(gè)斷點(diǎn)看一下各個(gè)變量的值也是很快能找到問(wèn)題的(直接跑也能看到錯(cuò)誤: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
要解決這種問(wèn)題也好辦,用一個(gè)可變的容器把要用的不可變類型的數(shù)據(jù)包裝一下就行了(說(shuō)個(gè)好久沒(méi)寫C#代碼記不太清楚完全不負(fù)責(zé)任的題外話,就像在C#.net里面,碰到閉包的時(shí)候,會(huì)自動(dòng)生成一個(gè)混淆過(guò)名字的類然后把要被捕捉的值當(dāng)作類的屬性存著,這樣在使用的時(shí)候就能輕松get,著名的老趙好像有一篇文章講Lazy Evaluation的好像涉及到這個(gè)話題):
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包裝后,程序能夠正常的工作,和預(yù)期的一致,其實(shí)我們也可以從函數(shù)的閉包的值再次確認(rèn):
>>> test.func_closure[1].cell_contents
{'retry_wait': 2, 'retry_times': 2}
我是結(jié)尾,PEACE!
相關(guān)文章
Python包中__init__.py文件的作用與用法實(shí)例詳解
我們新建python包時(shí)常常會(huì)看到一個(gè)__init _.py文件,下面這篇文章主要給大家介紹了關(guān)于Python包中__init__.py文件的作用與用法的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
Python基于回溯法解決01背包問(wèn)題實(shí)例
這篇文章主要介紹了Python基于回溯法解決01背包問(wèn)題,結(jié)合實(shí)例形式分析了Python回溯法采用深度優(yōu)先策略搜索解決01背包問(wèn)題的相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
python計(jì)算書頁(yè)碼的統(tǒng)計(jì)數(shù)字問(wèn)題實(shí)例
這篇文章主要介紹了python計(jì)算書頁(yè)碼的統(tǒng)計(jì)數(shù)字問(wèn)題實(shí)例,對(duì)比2個(gè)實(shí)例講述了數(shù)字統(tǒng)計(jì)的技巧,非常實(shí)用,需要的朋友可以參考下2014-09-09
Python實(shí)現(xiàn)合并多張圖片成視頻的示例詳解
隨著短視頻的興起,越來(lái)越多的人開始用各種形式進(jìn)行視頻制作,本篇博客從程序員的角度為大家解析一下如何通過(guò)?Python?合并多個(gè)圖片為一個(gè)視頻,需要的可以參考一下2023-02-02

