If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

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 :-)

Related slices

Comments (2)

  • Login to post

  • 0
    pang 6 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 smiley!

    replies (1)
    • manuele 6 years ago

      Thank you @pang! As I said in previous comment an easiest (and more pythonic) solution can be found... and you found it! :)

  • 0
    paulo 9 years ago

    Thanks for the share!

    replies (1)
    • manuele 9 years ago

      You're welcome Paulo, really I dodn't know if it was a really useful trick or just an exercise in style. Easiest solution can be used.

Hosting graciously provided by:
Python Anywhere