Python 判斷變量是否是 None 的三種寫(xiě)法
代碼中經(jīng)常會(huì)有變量是否為None的判斷,有三種主要的寫(xiě)法:
- 第一種是 if x is None ;
- 第二種是 if not x: ;
- 第三種是 if not x is None (這句這樣理解更清晰 if not (x is None) ) 。
如果你覺(jué)得這樣寫(xiě)沒(méi)啥區(qū)別,那么你可就要小心了,這里面有一個(gè)坑。先來(lái)看一下代碼:
- >>> x = 1
- >>> not x
- False
- >>> x = [1]
- >>> not x
- False
- >>> x = 0
- >>> not x
- True
- >>> x = [0]
- >>> not x
- False
- 復(fù)制代碼
在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都相當(dāng)于False ,即:
- not None == not False == not '' == not 0 == not [] == not {} == not ()
- 復(fù)制代碼
因此在使用列表的時(shí)候,如果你想?yún)^(qū)分 x==[] 和 x==None 兩種情況的話, 此時(shí) if not x:將會(huì)出現(xiàn)問(wèn)題:
- >>> x = []
- >>> y = None
- >>>
- >>> x is None
- False
- >>> y is None
- True
- >>>
- >>>
- >>> not x
- True
- >>> not y
- True
- >>>
- >>>
- >>> not x is None
- >>> True
- >>> not y is None
- False
- >>>
- 復(fù)制代碼
也許你是想判斷x是否為None,但是卻把 x==[] 的情況也判斷進(jìn)來(lái)了,此種情況下將無(wú)法區(qū)分。
對(duì)于習(xí)慣于使用if not x這種寫(xiě)法的pythoner,必須清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時(shí)對(duì)你的判斷沒(méi)有影響才行。
而對(duì)于 if x is not None 和 if not x is None 寫(xiě)法,很明顯前者更清晰,而后者有可能使讀者誤解為 if (not x) is None ,因此推薦前者,同時(shí)這也是谷歌推薦的風(fēng)格
結(jié)論:
if x is not None 是最好的寫(xiě)法,清晰,不會(huì)出現(xiàn)錯(cuò)誤,以后堅(jiān)持使用這種寫(xiě)法。
使用 if not x 這種寫(xiě)法的前提是:必須清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時(shí)對(duì)你的判斷沒(méi)有影響才行。