Why do 'and' & 'or' return operands in Python?

后端 未结 4 1954
遇见更好的自我
遇见更好的自我 2020-11-30 14:42

I\'m going through the LPTHW and I came across something I cannot understand. When will it ever be the case that you want your boolean and or or to

4条回答
  •  一整个雨季
    2020-11-30 15:39

    This has to do with the way short circuit effect is implemented in Python.

    With and (remember True and X = X), the result of the right expression is pushed into the stack, if it's false, it's get poped immediately, else the second expression is poped:

    >>> import dis
    >>> 
    >>> dis.dis(lambda : True and 0)
      1           0 LOAD_CONST               2 (True)
                  3 JUMP_IF_FALSE_OR_POP     9
                  6 LOAD_CONST               1 (0)
            >>    9 RETURN_VALUE
    >>>
    >>> True and 0
    0
    >>> 0 and True
    0
    >>>
    

    smiler to:

    def exec_and(obj1, obj2):
        if bool(obj1) != False:
            return obj2
        return obj1
    

    With or, if the first expression is true, it's get popped immediately. If not, the second expression is poped, now the result really depends on the second.

    >>> dis.dis(lambda : 0 or False)
      1           0 LOAD_CONST               1 (0)
                  3 JUMP_IF_TRUE_OR_POP      9
                  6 LOAD_CONST               2 (False)
            >>    9 RETURN_VALUE
    >>>
    >>> True or 0
    True
    >>> 1 or False
    1
    >>> False or 1
    1
    >>>
    

    smiler to:

    def exec_or(obj1, obj2):
        if bool(obj1) != True:
            return obj2
        return obj1
    

提交回复
热议问题