Python 2.5: Using any function

Here is a nice rewrite using Python 2.5 any function.

Before:

def isUpdate(self, sql):
    dml_words = [ 'INSERT', 'UPDATE', 'DELETE', 'REPLACE' ]
    sql_up = sql.upper()
    for word in dml_words:
        if sql_up.find(word) != -1:
            return True
    return False

After:

def isUpdate(self, sql):
    dml_words = [ 'INSERT', 'UPDATE', 'DELETE', 'REPLACE' ]
    sql_up = sql.upper()
    return any( sql_up.find(word) != -1 for word in dml_words )

any returns true if any of its items are true, e.g.:

a = 15
b = 20
any([a>5, b>5]) #True

values = [a, b]
any(v > 5 for v in values) #True

There's also all which returns true if all items are true:

a = 20
b = 3
all([a>5, b>5]) #False
Code · Interesting · Python · Tips 27. Dec 2007
© Amir Salihefendic. Powered by Skeletonz.