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

后端 未结 4 1959
遇见更好的自我
遇见更好的自我 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:34

    One would want and and or to evaluate to an operand (as opposed to always evaluating to True or False) in order to support idioms like the following:

    def foo(self):
        # currentfoo might be None, in which case return the default
        return self.currentfoo or self.defaultfoo()
    
    def foobar(self):
        # foo() might return None, in which case return None
        foo = self.foo()
        return foo and foo.bar()
    

    You can of course question the value of such idioms, especially if you aren't used to them. It's always possible to write equivalent code with an explicit if.

    As a point against them, they leave some doubt whether the full range of falsey values is possible and intentionally accounted for, or just the one mentioned in the comment (with other falsey values not permitted). But then, this is true in general of code that uses the true-ness of a value that might be something other than True or False. It occasionally but rarely leads to misunderstandings.

提交回复
热议问题