In this article, we will discuss the short-circuiting technique in Python programming.
What is Short Circuiting?
Short-circuiting is a technique many programming languages use when evaluating boolean logic expressions to save computing power by skipping unnecessary parts of the expression.
Python provides 2 short-circuit operators :
- or
- and
The or Operator
Python evaluates the left-hand side of the or
expression first. If it is True
, Python doesn’t evaluate the right-hand side because the entire expression will be True
regardless of the right-hand side.
50 > 20 or 0 > 1
Here, the first expression starting from left 50>20 is true. So Python will skip evaluating expressions on the right-hand side (0>1).
Another example :
a = True
b = False
result = a or b # Python only evaluates `a`, and the result is `True`
This avoids unnecessary computation on the right-hand side of the “or” operator.
The and Operator
For “and” operator, If the left-hand side expression is False
, Python doesn’t evaluate the right-hand side because the entire expression will be False
regardless of the right-hand side.
Let’s check the below example :
1 > 20 and 30 > 4
The left-hand side expression( 1>20) is False
so Python will skip evaluating right-hand side expressions.
How can we confirm that short-circuiting is skipping the computation?
The expression 1/0 raises an error(Division by zero) as shown below:
Python skips the 1/0 expression evaluation since 1>20 is False.
Similarly, we can confirm or operator short-circuiting too.
Here also division by zero is not raised because 1/0 is not evaluated.
Advantages of Short Circuiting in Python
1. Avoiding errors
Short-circuiting can help avoid errors by skipping unnecessary evaluations.
user = {'name': 'John', 'age': 30}
if user and user['address']:
print(user['address']['city'])
If user is None, accessing user[‘address’] would raise an error. But with short circuiting, the second part is only evaluated if user is true(Not None), preventing the error.
2. Improving Performance
Short-circuiting can improve performance by avoiding unnecessary computation..
if is_even(num) and is_prime(num):
print("Number is both even and prime")
If num is odd, checking if it’s prime is unnecessary, so short circuiting skips it.
3. Concise Conditional Logic
Short circuiting allows writing concise conditional logic. For example:
is_loaded = True
content = is_loaded and get_content()
If is_loaded is False, get_content() is never called, but content is still assigned False.
4. Assigning Default Values
Short circuiting is commonly used to assign default values:
user_name = user.get('name') or 'Anonymous'
If user.get(‘name’) returns None, user_name is assigned the default value ‘Anonymous’.
Conclusion
In summary, short circuiting in Python provides a way to write efficient, concise, and error-resistant code by skipping unnecessary computations based on the result of earlier parts of a boolean expression.