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?
PHP中文网2017-04-17 13:38:45
The content does not match the title. if x
and if 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 use if x is not None
.
As for if not x is None
and if x is not None
are the same, just choose the one that sounds smooth to you.
怪我咯2017-04-17 13:38:45
The former is closer to vernacular, while the latter may cause readers to misunderstand it as if (not x) is None
.
黄舟2017-04-17 13:38:45
First, check the opcode directly (XP+Python3.4).
Opcode for x is not None
:
dis.dis('if x is not None: pass')
0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 POP_JUMP_IF_FALSE 15
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
if not x is None
opcode:
dis.dis('if not x is None: pass')
0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 POP_JUMP_IF_FALSE 15
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
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 than if not x is None
. After all, there is a isn't in English.
PHPz2017-04-17 13:38:45
if not x is None
and if 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?).
PHP中文网2017-04-17 13:38:45
If your original x
is None
You need to execute the following code to determine whether x
has changed or is it still None
?
x = False
if x:
print 'yes'
else:
print 'no'
What you get will be no
, actually x
has been changed, but it is still False
if not x is None
and if 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