NoShortCircuit
Expressions with operators and
and or
always evaluate both of their operands.
and/or always evaluate both operands
and/or evaluate their right operand only if absolutely necessary
CorrectionHere is what's right.
These two operators are short-circuit operators, which means they first evaluate the left operand and then only evaluate the right operand if that’s absolutely necessary.
ValueHow can you build on this misconception?
Use in a common idiom
This misconception provides an opportunity to discuss the following idiom, which would cause an AttributeError
('NoneType'
object has no attribute 'value'
) if it always evaluated its right-hand operand, even when Node
is None
:
if node is not None and node.value < v:
...
Short circuiting also applies to chained comparisons. For example, if we have a comparison x < y <= z
and x < y
is False
then z
is not evaluated.