Fancy Python Tricks
- Last edited on Jul 21, 2014, 8:14:40 PM by Ffisegydd
not not
for bool conversions
Using two not
operators instead of the built-in bool
function is usually faster when wanting to convert some value to a boolean value:
>>> for t in ('bool(foo)', 'not not foo'):
timeit(t, setup='foo = 5')
0.3050157583752767
0.04769623091747577
Dynamic tree
A dynamic tree can be created by using a recursive defaultdict:
from collections import defaultdict
tree = lambda: defaultdict(tree)
t = tree()
t['dynamic']['path']['to']['something'] = 'foo'
print(t['dynamic']['path']['to']['something']) # foo