代码中常常会有变量是否为None的判断,有三种主要的写法:python
第一种是if x is None;
第二种是 if not x:;
第三种是if not x is None(这句这样理解更清晰if not (x is None)) 。
若是你以为这样写没啥区别,那么你可就要当心了,这里面有一个坑。先来看一下代码:this
>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0] # You don't want to fall in this one.
>>> not x
False
在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都至关于False ,即:code
代码以下:字符串
not None == not False == not '' == not 0 == not [] == not {} == not ()
所以在使用列表的时候,若是你想区分x==[]和x==None两种状况的话, 此时if not x:将会出现问题:class
>>> 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
>>>
也许你是想判断x是否为None,可是却把x==[]的状况也判断进来了,此种状况下将没法区分。变量
对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。ant
而对于if x is not None和if not x is None写法,很明显前者更清晰,然后者有可能使读者误解为if (not x) is None,所以推荐前者,同时这也是谷歌推荐的风格co
结论:字典
if x is not None是最好的写法,清晰,不会出现错误,之后坚持使用这种写法。
使用if not x这种写法的前提是:必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。字符