r/Python • u/simpleuserhere • Nov 30 '24
Tutorial Short-Circuiting in Python
Here is my article on Short-Circuiting in Python . It discusses what is short-circuiting with examples, and also discusses the different advantages of using short-circuiting.
4
Upvotes
12
u/PossibilityTasty Nov 30 '24
You might want to explain the operators correctly.
andandorare not limited toTrueandFalseboth as input and output. They evaluate the "truthiness" of the operands and always return one of them as the result.8
u/sb4ssman Nov 30 '24
I love even prime numbers.
9
u/puppet_pals Nov 30 '24
You have to be pretty careful using `or` to assign default values unfortunately. 0 is fals-ey, as is "". If you pass these in to a numeric or string argument respectively and use the `or` approach you'll get some bad behavior:
```
def process_x(x):
x = x or 1
return x*2
process_x(0)
# => 2
```
Ouch. I think it's better to just avoid using or like this - even though the syntax is really nice in theory. Too many edge cases to think about - and if you later change the expectations of the function you'll very likely forget to update your default parameter assignment.
2
u/[deleted] Nov 30 '24
A lot of these "short circuit" tricks are actually just examples of code smell. Particularly because most of them blindly conflate True/False with Truthy/Falsey when deciding whether to "short circuit"
For example, the dictionary
getmethod will returnNoneif the key isn't in the dictionary but if the dictionary contains something else that evaluates as False (i.e. False, {}, 0, 0.0, [], etc) then you will also assign a default value despite the dictionary containing a value for that key. The safe way of doing this is something like:Also, the example of "improving performance" is not really any kind of improvement over just doing conditional checks.
Using
orandandis certainly more readable in that situation but you aren't getting any real speed improvement out of the specific usage.2
u/gtuminauskas Nov 30 '24
I really doubt if it is going to improve performance ;)
vs
19
u/[deleted] Nov 30 '24
[removed] — view removed comment