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 (1)

  • Login to post



  • 0
    paulo 1 year ago

    Thanks for the share!

    replies (1)
    • manuele 1 year 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