2013-02-06 47 views
2

我不知道什么是好/最好的:最佳实践:断言指令()==假

>>> def command(): 
...  return False 
... 
>>> assert command() == False 
>>> assert command() is False 
>>> assert not command() 

干杯,马库斯

+0

是'command'函数吗?它返回boo l值? – iMom0

+0

@ iMom0在unittest上下文中,你经常有一个'command()'在测试中,它必须返回'False'。 – mhubig

+1

@mhubig:如果你使用PyUnit,'assertFalse()'方法可能是更好的风格。 – geoffspear

回答

2

最Python的是第三个。它等效于:

assert bool(command()) != False 
6

编码约定,可以在这里学习: PEP 8 Style Guide for Python Code

在那里,你会发现:

不要比较为真或假使用==

布尔值
Yes: if greeting: 
No: if greeting == True: 
Worse: if greeting is True: 
+1

为什么“True”被认为比“== True”更差? –

+1

所以这可能意味着'assert not command()'是最pythonic,因为@themiurgo说! – mhubig