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, [1], {"a": "n"}, "asdf", 2323]]'
1000000 loops, best of 3: 1.81 usec per loop
python -m timeit '[(not not t) for t in [[], {}, "", 0, [1], {"a": "n"}, "asdf", 2323]]'
1000000 loops, best of 3: 1.11 usec per loop
I tried to test it using this:
>>> [bool(t) == (not not t) for t in [None, [], {}, "", 0, [1], {'a': 'n'}, "asdf", 2323]]
[True, True, True, True, True, True, True, True, True]
And it seems to work for most common cases.
Arguments on readability aside, where does this fail, or why would this be a bad thing to do?
As Ignacio notes, both
bool()andnotinvoke 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
%timeitmagic method):And Paulo’s suggestion:
And one more, for funsies:
(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 Falseis faster.