One of the great new additions in python 2.7 is dictionary comprehensions. Unfortunately OpenERP still publicly wants python 2.5, and in reality runs on python 2.6 as a minimum in most installations. So if you are wanting to publish a module then python 2.7 style dictionary comprehensions are out. However it is fairly easy to approximate them using this trick.
Say you need to return a list of dictionaries, with id as the key and the field value as the value. A very common requirement with function fields, you will see code like this
def _get_attendee_count(self, cr, uid, ids, field, arg, context=None):
res = {}
for session in self.browse(cr, uid, ids, context=context):
res[session.id] = len(session.attendee_ids)
return res
Using a dictionary comprehension we can make this code much shorter and importantly faster. Simply write
def _get_attendee_count(self, cr, uid, ids, field, arg, context=None):
return dict([(session.id, len(session.attendee_ids) for session in self.browse(cr, uid, ids, context=context)])
OK not so simple lets break it down.
dict(lots of code) – casts our result as a dictionary
[lots of code] – starts and ends a standard python list comprehension
(session.id, len(session.attendee_ids) – creates a tuple which dict casts as {key: value}
for session etc is our loop condition.
So we end up with a list of tuples initial like [(1,4),(2,5),(13,8)] which dict transforms in to {1: 4, 2: 5, 13: 8}.
Same result, faster. Not for use everytime, as they can be hard to understand, but where the function is obvious, or the code is going to be run many times with lots of ids e.g. function fields in tree views they save a lot of time.
For the record what does a 2.7.2 dictionary comprehension look like (I’m not sure this is standard library but definitely is in Python 3).
return {session.id: len(session.attendee_ids) for session in self.browse(cr, uid, ids, context=context)}