Strange PEP8 recommendation on comparing Boolean values to True or False

前端 未结 6 1252
你的背包
你的背包 2020-12-06 04:54

At the end of python PEP8 I\'m reading:

  • Don\'t compare boolean values to True or False using ==

    Yes:   if greeting:
    No:    if g         
    
    
            
6条回答
  •  难免孤独
    2020-12-06 05:23

    Simplest reason to not compare truth via == or != comparisons seems to be this:

    0 is False # Result: False
    0 == False # Result: True; 0 evaluates comparatively to False
    
    1 is True  # Result: False  
    1 == True  # Result: True; 1 evaluates comparatively to True
    

    is checks whether the value passed is exactly True/False, not whether it evaluates to True or False.

    This behavior allows this:

    if var is False:
       # False (bool) case
    elif var is None:
       # None case
    elif var == 0:
       # integer 0 case
    

    whereas

    if var == False:
        # catches False & 0 case; but not None case, empty string case, etc.
    

    which seems counter-intuitive -- which is why I expect PEP8 says "don't do it".

    As said here use is for identity, but use == for equality.

    You'd only want to use if var is True when you need the bool value True, but want to reject 1, 'some string', etc.

    Such cases are probably not obvious to most readers; I suspect PEP8 claims it's "Worse" for being potentially misleading. From time to time it may be a necessary evil; but... if you find yourself needing is True, it may be indicating a design issue. In any case, you should probably comment "why" you need exactly True or False if you do ever use is.

提交回复
热议问题