本文完整示例程式碼及檔案已上傳至我的
Github
倉庫https://github.com/CNFeffery/PythonPracticalSkills
這是我的系列文章「Python實用祕技」的第5期,本系列立足於筆者日常工作中使用Python
積累的心得體會,每一期為大家帶來一個幾分鐘內就可學會的簡單小技巧。
作為系列第5期,我們即將學習的是:Python中短路機制的妙用
。

不同於物理學中的短路(Short circuit)那般危險,Python
中的短路機制非常有用,跟很多其他程式語言中的短路機制作用類似,一句話概括就是一段條件判斷表示式在從左到右按順序執行的過程中,提前確定了表示式的True/False結果,從而終止右邊剩餘的運算。
讓我們通過幾個簡單的例子總結Python
中可用的幾種短路機制:
- X or Y
X or Y
是最常用的短路機制,我們都知道只要X
或Y
中至少有一個為True
時,整段判斷表示式就為True
,譬如下面的例子中,本來1 / 0
會觸發ZeroDivisionError: division by zero
錯誤,但因為or
左邊的部分已經邏輯判斷為True
,Python
的短路機制就會停止後續的執行,直接返回or
左邊的結果:

而當or
左邊部分邏輯判斷為False
時,則會返回右邊部分的結果:

- X and Y
類似X or Y
的機制,X and Y
會在X
邏輯判斷為False
時提前終止後續的運算,只返回X
部分的結果:

- any()
Python
中的any()
函式用於接受序列形式的多個等待邏輯判斷的部分,並在序列中至少有一個部分邏輯判斷為True
時返回True
。
而只要any()
按順序遇到第一個邏輯判斷為True
的結果,也會觸發短路,正如下面的例子中只花費3秒就完成了判斷過程,因為迴圈到1
時觸發了短路:

- all()
Python
中的all()
函式類似any()
,會在傳入序列中每個部分邏輯判斷均為True
時返回True
,其也會在按順序遇到第一個False
時終止後續運算:

- 比較運算子
Python
中用於數值大小比較的各個運算子也具有短路機制,從左到右,一旦執行到判斷結果為False
的部分都會終止運算:

- 實際使用示例
當我們的程式碼中涉及到條件判斷,且參與條件判斷的值具有一定的運算成本時,就可以靈活運用短路機制來提升執行效率,譬如我們需要根據使用者id資訊向多個介面查詢其許可權,全部滿足時將其標記為“超級許可權”,就可以利用到短路機制。
這裡我們隨意寫幾個具有時間成本的函式作為介面示意:
def api1(id_):
time.sleep(1)
return id_ in ['admin1', 'admin2']
def api2(id_):
time.sleep(1)
return id_ in ['admin1', 'admin2', 'su1', 'su2']
def api3(id_):
time.sleep(1)
return id_ not in ['ban1', 'ban2', 'ban3']
利用短路機制在使用者第一次沒有滿足條件時就終止後續判斷,寫法簡潔:

本期分享結束,我們們下回見~?