google 的 python 风格指南中这么说:
Beware of writing
if x:
when you really meanif x is not None:
—e.g., when testing whether a variable or argument that defaults to None was set to some other value. The other value might be a value that's false in a boolean context!
也就是说,推荐使用 if x is not None
进行判断,but why?
内容和标题不符,
if x
和if not x is None
是不一样的。if x
会对x做 __nonzero__ 判断,当 x 为 ''(空字符串),{}(空字典), 0 的时候都是 False。当你确实要判断一个变量不是 None 的时候,应该用if x is not None
。至于
if not x is None
和if x is not None
是一样的,选一个你读的顺的就好。