Why do 'and' & 'or' return operand

2019-01-12 08:40发布

问题:

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 return something other than the boolean? The LPTHW text states that all languages like python have this behavior. Would he mean interpreted vs. compiled languages or duck typed vs static typed languages?

I ran the following code:

>>> False and 1
False
>>> True and 1
1
>>> 1 and False
False
>>> 1 and True
True
>>> True and 121
121
>>> False or 1
1
>>> False or 112
112
>>> False or "Khadijah"
'Khadijah'
>>> True and 'Khadijah'
'Khadijah'
>>> False or 'b'
'b'
>>> b = (1, 2, "K")
>>> b
(1, 2, 'K')
>>> False or b
(1, 2, 'K')
>>> 

Please help me understand whats going on here.

According to the documentation: http://docs.python.org/2/library/stdtypes.html

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

According to LPTHW: http://learnpythonthehardway.org/book/ex28.html Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True? Python and many languages like it return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.

回答1:

I think you're somehow confused about what the docs says. Take a look at these two docs sections: Truth Value Testing and Boolean Operators. To quote the last paragraph on the fist section:

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

As you can see, you're right about operations and built-in functions but see the Important exception part, it is well stated that the Boolean operators will return one of their operands.

Now, what they can return depends hardly on the operator's short circuit logic. For or operator, it will return the first truthy value in the expression, since when it finds one, the whole expression is true. In case of every operand being falsey, or will return the last operand, meaning that it iterated over every one of them not being able to find a truthy one.

For and operator, if the expression is true, it will return the last operand, if the expression is false, it will return the first falsey operand. You can read more about Short Circuit Evaluation at the Wikipedia Page.

You have a lot of examples in your question, let's analyze some of them:

>>> False and 1  # return false (short circuited at first falsey value)
False
>>> True and 1   # return 1 (never short circuited and return the last truthy value)
1
>>> 1 and False  # return false (short circuited at first falsey value, in this case the last operand)
False
>>> 1 and True  # return True (never short circuited and return the last truthy value)
True
>>> True and 121  # return 121 (never short circuited and return the last truthy value)
121
>>> False or 1  # return 1 (since the first operand was falsey, or kept looking for a first truthy value which happened to be the last operator)
1
>>> False or 112  # return 112 for same reason as above
112
>>> False or "Khadijah"  # return "Khadijah" for same reason as above
'Khadijah'
>>> True and 'Khadijah'  # return "Khadijah" because same reason as second example
'Khadijah'

I think this should make a point. To help you further understand why this is useful, consider the following example:

You have a function that randomly generate names

import random

def generate_name():
    return random.choice(['John', 'Carl', 'Tiffany'])

and you have a variable that you don't know if it has assigned a name yet so instead of doing:

if var is None:
    var = generate_name()

You can do oneliner:

var = var or generate_name()

Since None is a falsey value, or will continue its search and evaluate second operand, this is, call the function ultimately returning the generated name. This is a very silly example, I have seen better usages (although not in Python) of this kind of style. I couldn't come out with a better example right now. You can also take a look at this questions, there are very useful answers on the topic: Does Python support short-circuiting?

Last but not least, this has nothing to do with static typed, duck typed, dynamic, interpreted, compiled, whatever language. It's just a language feature, one that might come handy and that is very common since almost every programming language I can think of provide this feature.

Hope this helps!



回答2:

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.



回答3:

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


回答4:

Consider the following use case:

element = dict.has_key('foo') and dict['foo']

Will set element to dict['foo'] if it exists, otherwise False. This is useful when writing a function to return a value or False on failure.

A further use case with or

print element or 'Not found!'

Putting these two lines together would print out dict['foo'] if it exists, otherwise it will print 'Not found!' (I use str() otherwise the or fails when element is 0 (or False) because that s considered falsey and since we are only printing it doesn't matter)

This can be simplified to

print dict.has_key('foo') and str(dict['foo']) or 'Not found!'

And is functionally equivalent to:

if dict.has_key('foo'):
    print dict['foo']
else:
    print 'Not found!'