almost 2 years ago

Python: explicit versus implicit boolean conditions

In reviews I often call out implicit boolean conditions:

I usually wave my arms a bit, repeat "explicit is better than implicit", and maybe recall that one time this saved my bacon.

Now I have numbers to back me up.

Evaluating an implicit boolean condition is at least 80% slower than being explicit.

Well, for byte strings at least.

Let's try numbers:

Evaluating a number in an implicit boolean context is about 300% slower. That's actually a little weird how bad that is.

Next I put this in foo.py:

This is interesting:

Being implicit here only costs 5-20%.

I replaced foo.py with:

The purpose of __bool__ is for implicit boolean evaluation, so we can't compare implicit versus explicit here, but we can see that it's similar in speed to using __len__:

These timings are small enough that they're not going to hurt unless they're in a tight loop, say. But being explicit is a good habit to cultivate anyway <waves arms> and now you've got the excuse that it's faster.