I am studying a program by Peter Norvig, of AI book fame, found here and he uses this construction:
def candidates(word):
"Generate possible spelling corrections for word."
return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
I do understand how it works. For the sake of other readers, I will explain here.
Functions known, edits1 and edits2 return lists that can be empty.
The code uses the truth value of these lists to find the first that evaluates to True. Since Python short circuits the expression, that will be the answer.
But, for this expression to work, it is necessary that the operands are used as the return value, i.e. the lists will be kept as they are received, and not transformed to True or False while the logical expression is interpreted.
Another way to do that, using walrus, would be:
if a:=known([word]):
return a
elif b:=know(edits1(word)): #fixed elsif type on edit
return b
elif c:=know(edits2(word)): #fixed elsif type on edit
return c
else:
return [word]
I have two questions:
- Is the assumption that the value returned will be the original value of the operand, and not its truth value, the expected and correct behavior for any Python interpreter?
- Is this the Pythonic style?