Smart use of partial

I don't think a lot of people know the partial function - even if it's super useful! With a partial function you transform a function that takes multiple arguments into a function where some of those arguments are fixed.

An example:

def add(a, b):
   return a + b
print add(2, 2) #prints 4

add42 = partial(add, 42)
print add42(2) #print 44

I.e. add42 is a new function where a is 42.

I use partial all the time in JavaScript (AJS.partial or AJS.$p). And now I have started to use it in Python as well.

Python does not have a built-in partial function, but it's pretty easy to create one:

partial = lambda func, *args, **kw:\
              lambda *p, **n:\
                  func(*args + p, **dict(kw.items() + n.items()))

A real-world example

As a security constrain, I attach user_id check on most queries. A normal query could look like this:

db().upate('items', id=id, item_order=order, user_id=getUID())

Now, typing in user_id=getUID() is unneeded and very tiresome.

But partial is there to help! One can create a new function where user_id is fixed:

def sUpdate(table, **kw):
    fn = partial(db().update, where=['user_id=%s' % getUID()])
    return fn(table, **kw)

Having sUpdate it's now possible to only type:

sUpdate('items', id=id, item_order=order)

Smart :)

Code · Code improvement · Python · Tips 24. Feb 2007
© Amir Salihefendic. Powered by Skeletonz.