Is it safe to replace '==' with 'is' to compare Boolean-values

前端 未结 7 2126
谎友^
谎友^ 2020-12-08 06:26

I did several Boolean Comparisons:

>>> (True or False) is True
True
>>> (True or False) == True
True

It sounds like

7条回答
  •  隐瞒了意图╮
    2020-12-08 06:43

    Watch out for what else you may be comparing.

    >>> 1 == True
    True
    >>> 1 is True
    False
    

    True and False will have stable object ids for their lifetime in your python instance.

    >>> id(True)
    4296106928
    >>> id(True)
    4296106928
    

    is compares the id of an object

    EDIT: adding or

    Since OP is using or in question it may be worth pointing this out.

    or that evaluates True: returns the first 'True' object.

    >>> 1 or True
    1
    >>> 'a' or True
    'a'
    >>> True or 1
    True
    

    or that evaluates False: returns the last 'False' object

    >>> False or ''
    ''
    >>> '' or False
    False
    

    and that evaluates to True: returns the last 'True' object

    >>> True and 1
    1
    >>> 1 and True
    True
    

    and that evaluates to False: returns the first 'False' object

    >>> '' and False
    ''
    >>> False and ''
    False
    

    This is an important python idiom and it allows concise and compact code for dealing with boolean logic over regular python objects.

    >>> bool([])
    False
    >>> bool([0])
    True
    >>> bool({})
    False
    >>> bool({False: False})
    True
    >>> bool(0)
    False
    >>> bool(-1)
    True
    >>> bool('False')
    True
    >>> bool('')
    False
    

    Basically 'empty' objects are False, 'non empty' are True.

    Combining this with @detly's and the other answers should provide some insight into how to use if and bools in python.

提交回复
热议问题