In general this is a little trick to loop an operator on a list of arguments in the case you don't want or you can't consider the neutral element of the operator itself.
If you want for example to implement the sum of a list of integers the simpliest way is the following:
l = [1,2,3,4,5,6,7,8,9] r = 0 # the neutral element of sum for i in l: r += i
If you consider for example the "&" or "|" query operators for whom I don't know which is the rispective neutral element you can use the following method based on the associative property of the considered operator to obtain a query in which all conditions has to be verified.
from gluon import dal def querysum(*args): # considering to write this function in my modules I can get db from queries I pass as function arguments db = args[0]._db args1 = args[len(args)%2:] r = map(db._adapter.AND, args1[::2], args1[1::2]) while len(r) > 1: r = querysum(*r) if len(args)%2: # only if I have an odd number of arguments r = map(db._adapter.AND, r, args[:len(args)%2]) return dal.Query(db, *r)
I hope to be of any interest :-)
Comments (2)
0
pang 9 years ago
Can you post an example?
I don't really get it. Are you just joining the queries with "&"
How about
q = reduce((lambda a,b:a&b), args)
?
This one has a problem if args is empty, but your solution also has that problem... hard to solve because the empty query makes no sense !
replies (1)
0
paulo 12 years ago
Thanks for the share!
replies (1)