What are the differences between bool () and operator.truth ()?

bool() and operator.truth() both check if the value is true or false and they seem pretty similar from the docs, it even says in the truth() docs that:

This is equivalent to using the bool constructor.

However, truth() is twice as fast as bool() from a simple test (Python 3.6 timings are shown, but 2.7 is similar):

 from timeit import timeit print(timeit('bool(1)', number=10000000)) # 2.180289956042543 print(timeit('truth(1)', setup='from operator import truth', number=10000000)) # 0.7202018899843097 

So what is the difference? Should I use truth() instead of bool() ?

This Q&A came about after extensive comments and discussion with ShadowRanger on this issue .

+8
performance python boolean
source share
1 answer

Although bool() and operator.truth() produce the same result for the main use cases, their implementation is actually different. bool() is the constructor of a class or type, and truth() is a narrow optimized regular function.

In practical terms, there are also two differences: 1) bool() , called without arguments return False , and truth() is an argument. 2) bool() accepts the argument of the keyword x , for example bool(x=1) , and truth() does not accept the arguments of the keyword. Both of them add overhead for bool() for common use cases.

The implementation of the keyword is odd, since probably no one needs it, and the name x hardly descriptive. Issue29695 describes this, and in fact, the problem affects not only bool() , but also other classes, such as int() or list() . However, starting in Python 3.7, these keyword arguments will be removed, and speed should improve. However, I tested the timings in the last Python 3.8 branch, and bool() faster than before, but still twice as slow as truth() , presumably due to the more general implementation of bool() .

So, if you have a task where speed matters a lot, I would recommend using truth() over bool() if you need a function (for example, for parsing as a key to sorted() ). However, as khelwood points out , bool() can be faster, such as filter(bool, iterable) , so it is probably best to use the time of use one of the best options.

Of course, if you don’t need a function and you just want to check if the value is true or false, you should use idiomatic if or if not expressions, which are the fastest like helwood and user2357112 commented.

This Q&A came about after extensive comments and discussion with ShadowRanger on this issue .

+8
source share

All Articles