Sur un air de balisette



Filed under: programming, Python — Alexandre Fayolle @ 09:00

Interesting project Plumbum:

* Tomer Filiba’s blog post introducing Plumbum
* Plumbum documentation

Similar in goal to some of the modules living under the logilab.common package, with a nice and modern API (a lot of things in logilab.common were written before decorators were introduced… Heck, I started working on logilab.common at the time of python 1.5.2…)



setting default value in a python dictionary

Filed under: Python — Alexandre Fayolle @ 12:14

I encountered the following idiom in some OpenERP module recently:

some_dict['key'] = some_dict.get('key', {})

It struck me as an unusual way of setting a default value in a dictionary. So I investigated a bit to compare the performance of the construct compared to other ways of doing the same thing, in order to check if what I would have done (f2 below) was the most efficient way in addition to be the (in my opinion, at least) most readable. I used the timeit module and a few different dictionaries in case the presence of the key influenced the performance of the operation:

import timeit

def f1(d):
    d['value'] = d.get('value', {})

def f2(d):
    if 'value' not in d:
        d['value'] = {}

def f3(d):
    d.setdefault('value', {})

if __name__ == '__main__':
    for d in ('{}', "{'a': None, 'b': None}", "{'a': None, 'b': None, 'value': None}"):
        print d
        for i in (1, 2, 3):
            print "f%d" % i
            t = timeit.Timer('f%d(d)' % i,
                             'from __main__ import f1, f2, f3; d = %s' % d)
            print t.repeat()

With my local version (python 2.7.3), f1 is always the slowest, closely followed by f3, and the readable explicit version (f2) also runs 2x faster.

Blog at