DEV Community

Cover image for Short-circuit Evaluation Of Logical Expressions In Python
Enock kyei
Enock kyei

Posted on

Short-circuit Evaluation Of Logical Expressions In Python

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"
Image description
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
Image description
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.

Image description

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
Spongebob heading out meme

This is what "short-circuiting" the evaluation means.
This seems like a fine point and this clever technique is called the guardian pattern

Image description

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Hey! Thank you for this, I liked it ;) keep writing, you got my follow!

Collapse
 
kekyei profile image
Enock kyei

thank you