我不知道什麼是好/最好的:最佳實踐:斷言指令()==假
>>> def command():
... return False
...
>>> assert command() == False
>>> assert command() is False
>>> assert not command()
乾杯,馬庫斯
我不知道什麼是好/最好的:最佳實踐:斷言指令()==假
>>> def command():
... return False
...
>>> assert command() == False
>>> assert command() is False
>>> assert not command()
乾杯,馬庫斯
最Python的是第三個。它等效於:
assert bool(command()) != False
編碼約定,可以在這裏學習: PEP 8 Style Guide for Python Code
在那裏,你會發現:
不要比較爲真或假使用==
布爾值
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
爲什麼「True」被認爲比「== True」更差? –
所以這可能意味着'assert not command()'是最pythonic,因爲@themiurgo說! – mhubig
是'command'函數嗎?它返回boo l值? – iMom0
@ iMom0在unittest上下文中,你經常有一個'command()'在測試中,它必須返回'False'。 – mhubig
@mhubig:如果你使用PyUnit,'assertFalse()'方法可能是更好的風格。 – geoffspear