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?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
内容和标题不符,
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是一样的,选一个你读的顺的就好。前者更接近白话文,而后者有可能使读者误解为
if (not x) is None.首先,直接查看操作码(XP+Python3.4)。
x is not None的操作码:if not x is None的操作码:可以看到,操作码是一样的!
题主还可以测试后面加or或者and的情况。
个人意见,
if x is not None比if not x is None更加易读,毕竟英语当中有一个 isn't 呢。if not x is None和if x is not None對計算機而言是一樣的。對人類而言是不一樣的。前者的隱含意義是x本該是None結果不是,後者是x不該是None結果也不是。個人感覺,無客觀依據(好像沒有人做這樣的心理實驗?)。
前者更pythonic
假如原本你的
x为None你要执行如下代码判断
x是否已经发生改变,仍为None?你得到会是
no,其实x已经被改变了,但仍然是Falseif not x is None和if x is not None结果是一样的。if not x is None=>if not (x is None)if x is not None=>if x (is not) None