Skip to content Skip to sidebar Skip to footer

Where Would Typecasting To Boolean With `not Not` Instead Of `bool()` Fail?

To typecast a value to boolean, I usually do the following: not not value This is faster than using bool. Output from timeit: python -m timeit '[bool(t) for t in [[], {}, '', 0, [

Solution 1:

As Ignacio notes, both bool() and not invoke the same method (see operator.not_, __nonzero__,and the note there about __len__), so there's no need to compare them across different object types.

You'll get more accurate results if you test only the operator/function call (this is using ipython's %timeit magic method):

In [1]: %timeit not not 0
10000000 loops, best of 3: 60.2 ns per loop

In [2]: %timeit bool(1)
1000000 loops, best of 3: 180 ns per loop

In [3]: %timeit bool(0)
1000000 loops, best of 3: 177 ns per loop

In [4]: %timeit not not 1
10000000 loops, best of 3: 60.5 ns per loop

And Paulo's suggestion:

In [3]: %timeit True if 0 else False
10000000 loops, best of 3: 73 ns per loop

In [4]: %timeit True if 1 else False
10000000 loops, best of 3: 54.4 ns per loop

And one more, for funsies:

In [6]: %timeit 0 and True or False
10000000 loops, best of 3: 72.7 ns per loop

In [7]: %timeit 1 and True or False
10000000 loops, best of 3: 78.1 ns per loop

(all these tests were run against Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53), [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin)

So, to answer your question "would [using not not] be a bad thing to do": yes, definitely. If you care about readability, bool(…) is clearer, and if you care about performance, True if … else False is faster.


Solution 2:

Both operations invoke the same method (__nonzero__() on 2.x, __bool__() on 3.x), so both would have the same failure modes.


Post a Comment for "Where Would Typecasting To Boolean With `not Not` Instead Of `bool()` Fail?"