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?
The content does not match the title.
if x
andif not x is None
are different.if x
will make a __nonzero__ judgment on x. When x is '' (empty string), {} (empty dictionary), or 0, it will be False. When you really want to determine that a variable is not None, you should useif x is not None
.As for
if not x is None
andif x is not None
are the same, just choose the one that sounds smooth to you.The former is closer to vernacular, while the latter may cause readers to misunderstand it as
if (not x) is None
.First, check the opcode directly (XP+Python3.4).
Opcode for
x is not None
:if not x is None
opcode:As you can see, the operation codes are the same!
The questioner can also test the situation of adding or or and at the end.
Personally,
if x is not None
is easier to read thanif not x is None
. After all, there is a isn't in English.if not x is None
andif x is not None
are the same to the computer. It's different for humans.The implicit meaning of the former is that x should be None but is not, and the latter is that x should not be None but is not. Personal feeling, no objective basis (it seems no one has done such a psychological experiment?).
The former is more pythonic
If your original
x
isNone
You need to execute the following code to determine whether
x
has changed or is it stillNone
?What you get will be
no
, actuallyx
has been changed, but it is stillFalse
if not x is None
andif x is not None
have the same result.if not x is None
=>if not (x is None)
if x is not None
=>if x (is not) None