2013-02-06 51 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