Python的最佳实践:assert command()== False

mhu*_*big 2 python unit-testing assert

我想知道什么是更好/更好:

>>> def command():
...     return False
...
>>> assert command() == False
>>> assert command() is False
>>> assert not command()
Run Code Online (Sandbox Code Playgroud)

干杯,马库斯

Sch*_*huh 6

可以在此处研究编码约定: PEP 8 Python代码样式指南

在那里你会发现:

不要使用==将布尔值与True或False进行比较

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:
Run Code Online (Sandbox Code Playgroud)

  • 为什么 ``is True`` 被认为比 ``== True`` 更差? (3认同)
  • 所以这可能意味着 `assert not command()` 是最 Pythonic 的,正如 @themiurgo 所说! (2认同)

the*_*rgo 5

最Pythonic的是第三个。它相当于:

assert bool(command()) != False
Run Code Online (Sandbox Code Playgroud)