I read about a short-circuit behavior in python that strategically places a "guard" just before a logical expression that might cause an error after evaluation. The book said it's a clever technique called the "guardian pattern"
When Python is processing a logical expression, it
evaluates the expression from left to right because of the definition of "and", if x is less than 2, the expression x >= 2 is False and so the whole expression is False regardless of whether (x/y) > 2 evaluates to True or False
The first and the second examples did not fail because in the first calculation y was non zero. In the second one the first part of these expressions x >= 2 evaluated to False so the (x/y) was not even executed due to the short-circuit rule and there was no error. The third calculation failed because Python was evaluating (x/y) and y was zero, which causes a runtime error.
When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it stops and does not do the computations for the rest of the expression. In this case, since the first evaluation is false the whole expression will also be false regardless
This is what "short-circuiting" the evaluation means.
This seems like a fine point and this clever technique is called the guardian pattern
Top comments (2)
Hey! Thank you for this, I liked it ;) keep writing, you got my follow!
thank you