Search code examples
pythonbooleancomparison

Python - Implicit Boolean comparisons


I was reading the PEP 8 (Python . org), and I noticed that using implicit comparisons with Boolean was preferred.

if booleanCond == True     # Actually works
if booleanCond             # Works too but preferred according to PEP8

Those two statements mean the same, but in most languages I know explicit comparison is preferred. Can anyone explain me (quickly ?) why ?

Thanks !


Solution

  • AFAIK explicit comparison is frowned upon in most languages. There is a question about this practice on the Software Engineering stack exchange.

    The big picture is that if you need to explicitely compare your boolean condition to True you might have a naming problem with your variable.

    if is_blue: reads well (which is an important thing in python because it helps reduce the cognitive load of the programmer) and if is_blue is True: does not.

    As usual this is a heuristic and should not be dogmatic, but if you ever feel that you need to compare a boolean value to True or False to help your reader understand what you're doing it might be worth questionning your naming for this variable.