python:S2761 is not conducive to code runtime efficiency and compatibility

I thought python:S2761 is a choice between runtime efficiency and code readability.
That:
not not foo is much faster than bool(foo) and this can be verified through timeit.
What’s more, bool function first appeared in Python 2.2(year 2001) but not has a longer history since it appeared in Python 0.9(year 1991).
So I am working on a single piece of code that is compatible from Python 1.5 to Python 3.13.

Hello @cheny0y0 and welcome to this community!

It is true that not not foo is faster than bool(foo).

However, we believe that the clarity of the latter is preferable in most cases, as there can be no misinterpretation of the developer’s intent here, which is not the case when using not not (“Was the operator actually meant to be doubled?”). The reliability and maintainability benefits trump the performance gains in our opinion.

We also believe that usage of Python versions prior to 2.7.18 is quite rare and our products do make the assumption that either 2.7.18 or any 3.X version is being used.

It’s true that those assumptions may not suit every use case though. If the extra performance of the not not is important for your project or if you need to support Python versions older than 2.2, it makes sense to disable the rule in your project.

Hope that helps,
Guillaume

3 Likes